C# async/await chaining with ConfigureAwait(false)

青春壹個敷衍的年華 提交于 2019-11-29 09:59:46

Definitely not. ConfigureAwait just as it's name suggest configures the await. It only affects the await coupled with it.

ConfigureAwait actually returns a different awaitable type, ConfiguredTaskAwaitable instead of Task which in turn returns a different awaiter type ConfiguredTaskAwaiter instead of TaskAwaiter

If you want to disregard the SynchronizationContext for all your awaits you must use ConfigureAwait(false) for each of them.

If you want to limit the use of ConfigureAwait(false) you can use my NoSynchronizationContextScope (see here) at the very top:

async Task CallerA()
{
    using (NoSynchronizationContextScope.Enter())
    {
        await Method1Async();
    }
}

When the task is awaited, it creates a corresponding TaskAwaiter to keep track of the task which also captures the current SynchronizationContext. After the task completes, the awaiter runs the code after the await ( called the continuation) on that captured context.

You can prevent that by calling ConfigureAwait(false), which creates a different kind of awiatable (ConfiguredTaskAwaitable) and its corresponding awaiter (ConfiguredTaskAwaitable.ConfiguredTaskAwaiter) that does not run the continuation on the captured context.

The point is that for each await, a different instance of an awaiter is created, it is not something that is shared between all the awaitables in the method or program. So it's best that you call ConfigureAwait(false) for each await statement.

You can see the source code for the awaiters here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!