Skip to content

Latest commit

 

History

History
41 lines (24 loc) · 1.57 KB

File metadata and controls

41 lines (24 loc) · 1.57 KB

ConfigureAwait Tutorial

Usually, it is a good practice to call ConfigureAwait(false) after each async call to prevent a small performance impact. This is safe to do when you know for sure that there is no context to be preserved and restored.

1) The problem

Suggested Practice

When calling an async method, it is a good practice to also call ConfigureAwait(false), to prevent a small performance impact.

But not always

The above statement is true only if we know for sure that there is no context needed to be preserved and restored.

On the other hand, in a WPF application when the UI needs to be updated or the ASP.NET application when the HttpContext.Current instance is needed after the async call, we cannot use ConfigureAwait(false).

ASP.NET

In ASP.NET, after the execution of an async method with ConfigureAwait(false), the HttpContext.Current static instance is null.

public async Task<IEnumerable<string>> Get()
{
    HttpContext before = HttpContext.Current;

    IEnumerable<string> values = await GetValuesAsync()
        .ConfigureAwait(false);

    HttpContext after = HttpContext.Current; // this is null

    return values;
}

ASP.NET Core

ASP.NET Core does not have this problem because it provides the HttpContext instance as property on the controller.

Libraries

In the methods that do not use, directly or indirectly, the static HttpContext.Current instance, it is safe, even useful, to call ConfigureAwait(false) to avoid the performance penalty involved in saving/restoring context because there isn't one to restore.