Skip to content

In Case You Missed It (ConfigureAwait)

In Case You Missed It is a periodic series of cool tidbits, reminders and things I have found useful in coding.

I recently picked up this valuable little tidbit from a developer I had the pleasure to work with. I can’t believe that I hadn’t known this before, but when I found out that several other developers I have worked with before weren’t aware of it either, I stopped feeling quite so foolish…

ConfigureAwait on the end of an awaited call can serve many purposes. First of all, it helps to avoid deadlocks by enabling a small amount of parallelism and ensure that it runs in parallel with the GUI main thread, the second is that it stops the continuous check-ins with the main thread, thereby ensuring optimal performance with no UI hiccups.

It does this by ensuring a consistent context for the running code. Awaited calls without ConfigureAwait check back into the main thread (GUI) at the completion of their run and subsequent calls to that context can result in deadlocks.

The syntax is simple:

await Task.Delay(500).ConfigureAwait(continueOnCapturedContext: false);

or just:

await Task.Delay(500).ConfigureAwait(false);

One other important thing to note is that once you invoke ConfigureAwait in a method, it is best to do it for every awaited call after that point in the method. This ensures a more consistent flow in the way the code runs and allows the code to continue to execute in parallel without checking back in to the GUI or main thread.

You should, however, avoid ConfigureAwait if you have to use the context of the method after the await. This is especially true for apps with a user interface. Any code that is used to affect GUI elements or is involved in updating bound properties or needs access to GUI-specific types such as Dispatcher/CoreDispatcher should not use ConfigureAwait.

ConfigureAwait is a powerful little tool in the Async arsenal, used wisely it will make your users’ experiences much better!

Hope this helps.

Posted in In Case You Missed It, Periodic Post Series.

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

or, reply to this post via trackback.