gpt4 book ai didi

.net - 我可以在.NET 4.7.2 Web API 中删除ConfigureAwait(false) 吗?

转载 作者:行者123 更新时间:2023-12-02 01:49:59 25 4
gpt4 key购买 nike

我正在检查一些使用 .NET 4.7.2 的 ASP.NET Web API 代码。

这是一个示例 Controller 和操作方法:

  public class ThingController : System.Web.Http.ApiController
{
// ...

public async Task<IHttpActionResult> GetValue()
{
var value = await _db.GetValue().ConfigureAwait(false);
return Content(value);
}
}

我读过best practice是不要在应用程序代码中使用 ConfigureAwait ,以便继续执行捕获的同步上下文,因为可能需要状态 associated with the captured context 。不过,一般来说,我们应该使用 ConfigureAwait(false),这样我们就不会不必要地继续捕获的同步上下文。

所以我的想法是,我们不想在此 Web API 代码中的任何位置调用 ConfigureAwait(false)

然后我读到了 deadlocksdoesn't matter when using ASP.NET Core (虽然我不是)。

我添加了一个断点并检查了 SynchronizationContext.Currentnull

我可以安全地从此项目中删除对 ConfigureAwait(false) 的所有调用吗?如果不是,在什么情况下应该保留这些调用?

最佳答案

I have read that best practice is to not use ConfigureAwait in application code so that execution continues with the captured synchronization context, since there may be needed state associated with the captured context. However, in general we should use ConfigureAwait(false) so that we don't continue on the captured synchronization context unnecessarily.

我想说,最佳实践是在库中使用 ConfigureAwait(false),它可以在不同的上下文中使用。对于应用程序代码,ConfigureAwait(false) 通常是不必要的。 (在某些高级情况下,出于性能原因,需要 ConfigureAwait(false),但这种情况很少见)。

So my thoughts are that we don't want to be calling ConfigureAwait(false) anywhere in this Web API code.

我同意。除了 Controller 方法之外,我通常在所有可以使用的地方使用 ConfigureAwait(false),但您可以扩展“不使用 ConfigureAwait(false)”规则以包括所有 应用程序代码。

Then I read about deadlocks...

Deadlocks (如我的博客中所述)需要两个部分:

  1. 单线程上下文。在 ASP.NET 中,SynchronizationContext 是单线程上下文。
  2. 在该上下文中阻塞线程,等待一些需要该上下文的代码。这部分通常是由“同步优于异步”反模式引起的。

在您的代码中,不存在异步同步,因此无论是否使用 ConfigureAwait(false) 都不可能出现死锁。

I've added a breakpoint and checked SynchronizationContext.Current which is null...HttpContext.Current is null before the call, in fact upon entry to the method.

实际上,这是一个非常有问题的问题。请查看this article并确保您已完成在 ASP.NET 上使用异步代码的所有先决条件。特别是,您必须对 httpRuntime.targetFrameworkaspnet:UseTaskFriendlySynchronizationContext 进行适当的设置。

关于.net - 我可以在.NET 4.7.2 Web API 中删除ConfigureAwait(false) 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70438507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com