Beware: asynchrony with monogame

The async / await keywords allow asynchrony extremely easily in comparison to previous implementations; however, this blog post is a word of caution for those working with monogame or XNA in general.

Imagine the following update method:

                try
                {
                    spriteBatch.Begin( SpriteSortMode.Deferred, BlendState.AlphaBlend);                   
                    await UpdateMySprites(spriteBatch);
                    await HandleInput();
                }
                finally
                {
                    spriteBatch.End();
                }

Okay, so this is spot on: where `UpdateMySprites` takes some time, it won’t stall execution… except that it will.

Why?

Because of the way `async` works. What the await function actually does is create a continuation block, which includes:

    spriteBatch.End();

As a result, the screen is not drawn until the slow function finishes (whether the function should be that slow at this part of the code is another matter).

So, how to fix? Well, one option is to simply not await the functions. You can prevent yourself from doing that by not making the Update function `async`. You can still call asynchronous functions from a non-async method, but you can’t await them. The compiler will give you a warning and, to be honest, it’s probably not the best practice (you pay in your ability to work out exactly what state your program is in).

Another option is to make this method synchronous; and, where it needs to be asynchronous, use a background worker.

Conclusion

Although it seems straightforward (at least it does if you understand async), this did take me a while to work out. Hopefully it’ll save you that time.

Games are not the same as apps and utilities. Although many things may occur at the same time, you really need to know what all of those things are and exactly what position or state they are in; maybe using asynchrony in game development in a bad idea.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.