返回工作或等待和ConfigureAwait(假) [英] Return Task or await and ConfigureAwait(false)

查看:206
本文介绍了返回工作或等待和ConfigureAwait(假)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个服务库,像这样的方法

Suppose to have a service library with a method like this

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

以下为最佳实践的的SynchronizationContext 的是更好地使用

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

但是,当你只有一个操作(我认为)是更好地直接返回任务。见<一href=\"http://stackoverflow.com/questions/17886992/at-the-end-of-an-async-method-should-i-return-or-await\">At异步方法结束时,我应该返回或等待?

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

在最后这种情况下,你不能使用的 ConfigureAwait(假)的,因为该方法不会等待。

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

什么是最好的解决方案(为什么)?

What is the best solution (and why)?

推荐答案

每个选项都有自己的具体情况,请检查这个。如果你了解他们,你可以决定什么是对你最好的之一。

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

这样返回任务的解决方案,直接不捕获
  SynchronizationContext的?

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

这不是捕获当前同步上下文的任务。这是<一个href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.taskawaiter.oncompleted%28v=vs.110%29.aspx\"><$c$c>TaskAwaiter.OnCompleted (或 ConfiguredTaskAwaitable.OnCompleted ,在以下情况下 ConfigureAwait ),这是间接所产生的code调用C#编译器作为任务的等待语句的一部分。

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.

所以,如果你不使用等待,你不应该担心的SynchronizationContext 捕捉,它不会奇迹般地发生在自己的。这可能使得第三选择最有利的一个,但记住其异常传播行为

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.

这篇关于返回工作或等待和ConfigureAwait(假)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆