C# - ConfigureAwait(false)

language-features csharp

What is the deal with ConfigureAwait(false)?

It determines the thread on which the code continues to execute after the await statement returns.

What does it look line?

async Task MyMethodAsync()
{
  // Code here runs in the original context.
  await Task.Delay(1000);
  // Code here runs in the original context.
  await Task.Delay(1000).ConfigureAwait(
    continueOnCapturedContext: false);
  // Code here runs without the original
  // context (in this case, on the thread pool).
}

When should we use it?

The recommendation is to always use it in library code and not in UI/GUI code.

Because it is assumed that the library code will be used in different types of applications and capturing the original thread context is not important.

Because capturing the SynchronizationContext is very important in GUI apps. You do not want to do this:

private async void button1_Click(object sender, EventArgs e)
{
  button1.Enabled = false;
  try
  {
    // Can't use ConfigureAwait here ...
    await Task.Delay(1000);
  }
  finally
  {
    // Because we need the context here.
    button1.Enabled = true;
  }
}

Any other weird detail?

ConfigureAwait configures the await not the task.

Continue Reading