Best practice to call ConfigureAwait for all server-side code

前端 未结 4 706
既然无缘
既然无缘 2020-11-22 04:06

When you have server-side code (i.e. some ApiController) and your functions are asynchronous - so they return Task - is it consid

4条回答
  •  盖世英雄少女心
    2020-11-22 04:29

    I have some general thoughts about the implementation of Task:

    1. Task is disposable yet we are not supposed to use using.
    2. ConfigureAwait was introduced in 4.5. Task was introduced in 4.0.
    3. .NET Threads always used to flow the context (see C# via CLR book) but in the default implementation of Task.ContinueWith they do not b/c it was realised context switch is expensive and it is turned off by default.
    4. The problem is a library developer should not care whether its clients need context flow or not hence it should not decide whether flow the context or not.
    5. [Added later] The fact that there is no authoritative answer and proper reference and we keep fighting on this means someone has not done their job right.

    I have got a few posts on the subject but my take - in addition to Tugberk's nice answer - is that you should turn all APIs asynchronous and ideally flow the context . Since you are doing async, you can simply use continuations instead of waiting so no deadlock will be cause since no wait is done in the library and you keep the flowing so the context is preserved (such as HttpContext).

    Problem is when a library exposes a synchronous API but uses another asynchronous API - hence you need to use Wait()/Result in your code.

提交回复
热议问题