Search code examples
async-awaitconfigureawait

Cascading ConfigureAwait(false), is it necessary?


I am developing an MVC5 ASP.NET Application where I have the following question.

If I have an action in a controller defined this way:

public async Task<ActionResult> MyAction()
{
    await MethodAsync().ConfigureAwait(false);
}

Then, if MethodAsync calls another async method, this way:

public async Task<bool> MethodAsync()
{
    await OtherMethodAsync().ConfigureAwait(false);
}

Does it make sense to call again ConfigureAwait(false) inside the awaited method? Or should I use the default (ConfigureAwait(true))?.

Thanks Jaime


Solution

  • Each method should make its own decision on whether to use ConfigureAwait(false). If that method needs its context (in this case, HttpContext.Curent / culture / identity), then it should not use ConfigureAwait(false).

    Bear in mind that this code:

    await MethodAsync().ConfigureAwait(false);
    

    is roughly the same as this code:

    var task = MethodAsync();
    var configuredTask = task.ConfigureAwait(false);
    await configuredTask;
    

    In other words, MethodAsync is called before ConfigureAwait. So the method is called with the current context, and then the task it returned is awaited without capturing the context.