0Pricing
C# Academy · Lesson

ConfigureAwait, exception flow

Understand context capture and ConfigureAwait(false); handle exceptions with await vs blocking; see AggregateException and best practices.

Context & exceptions

Goals:

  • Know what context capture is
  • When to use ConfigureAwait(false)
  • How exceptions flow with await
  • Why blocking leads to AggregateException

Library best practice

Library methods should use ConfigureAwait(false) to avoid resuming on a UI/web context they do not own.

using System;
using System.Threading.Tasks;

public static class NetLib
{
  // Library code should not assume a UI context. Use ConfigureAwait(false).
  public static async Task<string> FetchAsync()
  {
    await Task.Delay(100).ConfigureAwait(false); // do not capture context
    return "payload";
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    // Console apps typically have no SynchronizationContext; this still runs fine.
    string s = NetLib.FetchAsync().GetAwaiter().GetResult();
    Console.WriteLine("Got: " + s);
  }
}

All lessons in this course

  1. Task/ValueTask and the async state machine (concepts)
  2. Async pitfalls: sync-over-async and deadlocks
  3. ConfigureAwait, exception flow
← Back to C# Academy