title: How do you stop SoundEffect from crashing XNA windows games when they are closed?
body: <p>I am creating a game for windows in xna using Visual C# Express. In the game, there are six SoundEffect objects which regularly have their Play() methods called.  The problem is that sometimes when the game is closed it crashes. <strong><em>It appears to happen whenever the window is closed while a soundeffect is playing.</em></strong> This is the message which pops up in Visual C#:</p>
  
  <p><strong>AccessViolationException was unhandled</strong></p>
  
  <p><em>Attempted to read or write protected memory. This is often an indication that other memory is corrupt.</em></p>
  
  <p>There isn't any source available in visual studio to debug and when the "get general help for this exception" is clicked, a blank page pops up..</p>
  
  <p>The code used looks a lot like the MSDN example. This looks like a problem that exists somewhere in the underlying framework somewhere, not my code. But of course I don't know for sure. This has happened many times. </p>
  
  <p><a href="http://msdn.microsoft.com/en-us/library/bb195053.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb195053.aspx</a> </p>
  
  <p>Here are the complete exception details:</p>
  
  <pre><code>System.AccessViolationException was unhandled
    Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
    Source=Microsoft.Xna.Framework
    StackTrace:
         at Microsoft.Xna.Framework.Audio.AudioCallbackDispatcher.IsEventRegistered(EventType type)
         at Microsoft.Xna.Framework.Audio.AudioCallbackDispatcher.UnregisterEvent(EventType type)
         at Microsoft.Xna.Framework.Audio.KernelMicrophone.ShutdownCaptureEngine()
         at Microsoft.Xna.Framework.Audio.MicrophoneUnsafeNativeMethods.ShutdownCaptureEngine()
         at Microsoft.Xna.Framework.Audio.AudioRendererShutdownHandler.AppExitingEventHandler(Object sender, EventArgs args)
    InnerException:
  </code></pre>
  
  <p>(I also have music playing via MediaPlayer, but I don't think it's related.)</p>
  
  <p>EDIT: I seem to have found something which works, but it's kind of hackish and really shouldn't be necessary. I'm still open to any more elegant solutions.</p>
  
  <p>Call this line in Game1.UnloadContent(). It will make sure (if your sound effects are all shorter than 3 seconds) that no sound is playing when the program actually closes.</p>
  
  <pre><code>System.Threading.Thread.Sleep(3000);
  </code></pre>