Warning: Undefined array key 37 in /usr/www/maxtingle/Blog/System/Core/BlogPost.php on line 71

Warning: Undefined array key 37 in /usr/www/maxtingle/Blog/System/Core/BlogPost.php on line 76
Max Tingle's Website - C# The mystery of the MediaPlayer AppCrash
C# The mystery of the MediaPlayer AppCrash
Created by maxtingle on Sat 3rd May 2014 in category C#. 1314 Views | Tags: C#, MediaPlayer, GameEngine
During the development of my game engine, I discovered that System.Media.SoundPlayer had a nasty catch, it was simply hooking into a PlaySound function that Windows implements and that function only supports a single sound. Because of this I had to move onto a better player, System.Media.MediaPlayer, but this made me come toe to toe with another nasty problem, the lack of looping support. So I went along and implemented looping through the MediaEnded event and some simple functions.

All was well and dandy until I discovered that when I used Visual Studio's debugging tools to run my test game, it crashed upon exit. That is, after my custom SoundPlayer class had an instance created of it. It was an AppCrash, the error coded pointed towards an out of memory error and the DLL at fault was the Kernel.

My first idea was to implement System.IDisposable, my logic was that the sound continued calling the underlying PlaySound method after being asked to close by its parent and since MediaPlayer didn't implement IDisposable its self I had to do it myself.

Here is my first implementation:
public void Dispose()
{
    this.Stop();
    this.Close();
}
It simply stops the current sound and then tells the base class (MediaPlayer) to free the file being used and close the media. I thought it would work, because hey, why wouldn't it? It did not and I was presented with the same nasty error code. I tried looking around online and even posted on StackOverflow, but it was only after I took at look at the Dispatcher variable in the base class that I found what I was looking for. MediaPlayer operates on separate threads so it doesn't stop the main thread from continuing its work and Dispatched is that thread. Wielding this new knowledge I added another line to my Dispose method, resulting in:
public void Dispose()
{
    this.Stop();
    this.Close();
    this.Dispatcher.InvokeShutdown();
}
And it worked! It shut down the thread and the application closed without Windows having to force it too, WHOO! Another day, another silly bug.


Comments

Sign up to comment!

Warning: Undefined array key "Viewed" in /usr/www/maxtingle/Blog/System/Blog.php on line 57

Warning: Undefined array key "Viewed" in /usr/www/maxtingle/Blog/System/Blog.php on line 60