Return Task or await and ConfigureAwait(false)

霸气de小男生 提交于 2019-12-18 14:54:34

问题


Suppose to have a service library with a method like this

public async Task<Person> GetPersonAsync(Guid id) {
  return await GetFromDbAsync<Person>(id);
}

Following the best practices for the SynchronizationContext is better to use

public async Task<Person> GetPersonAsync(Guid id) {
  return await GetFromDbAsync<Person>(id).ConfigureAwait(false);
}

But when you have only one operation (I think) is better to return the Task directly. See At the end of an async method, should I return or await?

public Task<Person> GetPersonAsync(Guid id) {
  return GetFromDbAsync<Person>(id);
}

In this last case you can't use ConfigureAwait(false) because the method is not awaited.

What is the best solution (and why)?


回答1:


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.



来源:https://stackoverflow.com/questions/23536848/return-task-or-await-and-configureawaitfalse

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