0
0
C Sharp (C#)programming~5 mins

ConfigureAwait behavior in C Sharp (C#)

Choose your learning style9 modes available
Introduction

ConfigureAwait controls if an awaited task continues on the original context or not. It helps avoid deadlocks and improve performance.

When you want to avoid blocking the UI thread in a desktop app.
When writing library code that should not depend on a synchronization context.
When you want to improve performance by not capturing the current context.
When you want to prevent deadlocks caused by waiting on async code synchronously.
When you want to explicitly continue on the original context for UI updates.
Syntax
C Sharp (C#)
await someTask.ConfigureAwait(continueOnCapturedContext);

continueOnCapturedContext is a boolean: true means resume on the original context, false means resume on any thread.

By default, ConfigureAwait(true) is used, which captures the current context.

Examples
Does not resume on the original context after the delay.
C Sharp (C#)
await Task.Delay(1000).ConfigureAwait(false);
Resumes on the original context after the delay (default behavior).
C Sharp (C#)
await Task.Delay(1000).ConfigureAwait(true);
Awaits an async method without capturing the context, useful in library code.
C Sharp (C#)
var result = await SomeAsyncMethod().ConfigureAwait(false);
Sample Program

This program shows that in console apps (no synchronization context), ConfigureAwait(false) and ConfigureAwait(true) both result in continuations on thread pool threads (different from the original main thread).

C Sharp (C#)
using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.WriteLine($"Main thread id before await: {Thread.CurrentThread.ManagedThreadId}");

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

        Console.WriteLine($"Thread id after await with ConfigureAwait(false): {Thread.CurrentThread.ManagedThreadId}");

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

        Console.WriteLine($"Thread id after await with ConfigureAwait(true): {Thread.CurrentThread.ManagedThreadId}");
    }
}
OutputSuccess
Important Notes

In UI apps, ConfigureAwait(false) helps avoid freezing the UI by not resuming on the UI thread.

In console apps, there is usually no synchronization context, so ConfigureAwait(false) has less effect.

Always use ConfigureAwait(false) in library code to avoid unexpected context dependencies.

Summary

ConfigureAwait controls if the continuation runs on the original context or not.

Use ConfigureAwait(false) to improve performance and avoid deadlocks.

Use ConfigureAwait(true) (default) when you need to resume on the original context, like UI updates.