A quest for software excellence...

Context Switching and Task<Result>.ConfigureAwait Method

While heavily involved in a few ASP.NET Web API 2 projects over the past year, I’ve learned from experience that context switching, marshaling between threads when using the async and await constructs in C# can be undesirable.

To avoid the context switching which is undeniably needed in a UI application where you’re offloading work from the UI thread, the default value of “true” for the ConfigureAwait Method on the Task<Result> class, one must set the “continueOnCapturedContext” to false. Like this:

var user = await repo.GetUser(id).ConfigureAwait(false);

There is some debate as to whether this is helpful in an ASP.NET application given the request is handled on a thread pool thread which is returned to the pool while the asynchronous task is running.

The issue I’ve noticed is that in some cases setting the “continueOnCapturedContext” to false, eliminates the need to marshal the continuation of your code back to the original context and use of another thread pool thread. While there are no noticeable performance advantages, I have noticed that I experience fewer threading exceptions when I allow the execution to continue on the thread that just executed my asynchronous work.