C# async/await chaining with ConfigureAwait(false)

后端 未结 2 619
無奈伤痛
無奈伤痛 2020-12-19 02:01

Based on numerous books and blogs including this excellent one here, it is clear that when one writes a dll library exposing helper async methods i.e. the wrapper methods, i

2条回答
  •  太阳男子
    2020-12-19 02:30

    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();
        }
    }
    

提交回复
热议问题