Return Task or await and ConfigureAwait(false)

前端 未结 1 1044
长情又很酷
长情又很酷 2021-01-01 23:00

Suppose to have a service library with a method like this

public async Task GetPersonAsync(Guid id) {
  return await GetFromDbAsync

        
相关标签:
1条回答
  • 2021-01-01 23:29

    Each option has its own specifics, check this and this. If you understand them, you could decide what's the best one for you.

    So the solution that return the Task directly doesn't capture the SynchronizationContext?

    It's not the task that captures the current synchronization context. It's TaskAwaiter.OnCompleted (or ConfiguredTaskAwaitable.OnCompleted, in case of ConfigureAwait), which is indirectly invoked by the code generated by C# compiler as a part of the await statement for the task.

    So, if you don't use await, you shouldn't be worried about SynchronizationContext capturing, it doesn't magically happen on its own. This probably makes the 3rd option the most favorable one, but keep in mind its exception propagation behavior.

    0 讨论(0)
提交回复
热议问题