Lock contention during load screen animations

Originally posted to Shawn Hargreaves Blog on MSDN, Friday, May 23, 2008

If your game has a lot of content, your LoadContent call might take a while.

If loading takes a long time, you might want to display a "please wait" message.

If you value polish, you might even decide this message should be animated in some kind of awesomely cool way.

It is pretty easy to do that by firing up a background thread at the start of LoadContent, and having it do something like:

    while (!finishedLoading)
    {
        DrawFunkyLoadingAnimation();
        GraphicsDevice.Present();
    }

Here be dragons! The above code will work, but is liable to make your loading hundreds of times slower.

The reason is that every time you touch the graphics device from a different thread, the framework takes out a critical section, in order to avoid heisenbadness. If the animation is constantly redrawing, the animation thread will pretty much always own this lock, so any time your load function wants to create a graphics resource such as a texture, vertex buffer, or shader, it must wait until the animation thread releases it. This might take a while if the animation thread is just constantly looping over the same piece of draw code!

The solution is to slow down your animation thread by inserting a sleep call, which stops it hogging the graphics device.

The animated LoadingScreen class in our Network State Management sample shows one way to implement this.

Blog index   -   Back to my homepage