C# - ConfigureAwait(ConfigureAwaitOptions)

language-features csharp

What is it?

It is a new flag enum.

namespace System.Threading.Tasks;
[Flags]
public enum ConfigureAwaitOptions
{
    None = 0x0,
    ContinueOnCapturedContext = 0x1,
    SuppressThrowing = 0x2,
    ForceYielding = 0x4,
}

Explain using a short example:

// These all do the same thing
await task;
await task.ConfigureAwait(continueOnCapturedContext: true);
await task.ConfigureAwait(ConfigureAwaitOptions.ContinueOnCapturedContext);


// These do the same thing
await task.ConfigureAwait(continueOnCapturedContext: false);
await task.ConfigureAwait(ConfigureAwaitOptions.None);

// Default behavior (no ConfigureAwait): continue on the captured context.
await task;

// Default flag option (None): do not continue on the captured context.
await task.ConfigureAwait(ConfigureAwaitOptions.None);

// These do the same thing
await task.ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
try { await task.ConfigureAwait(false); } catch { }

What is ForceYielding?

The normal behavior for await is to check if the awaitable is complete, and if it is, then continue executing synchronously; ForceYielding prevents that synchronous behavior, forcing the await to behave asynchronously.

Continue Reading