【发布时间】:2023-03-30 23:06:01
【问题描述】:
我正在检查一些使用 .NET 4.7.2 的 ASP.NET Web API 代码。
这是一个示例控制器和操作方法:
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)。
然后我读到了deadlocks 和doesn't matter when using ASP.NET Core(虽然我不是)。
我添加了一个断点并检查了SynchronizationContext.Current,即null。
我可以安全地从该项目中删除对ConfigureAwait(false) 的所有调用吗?如果不是,在哪些情况下应该保留这些调用?
【问题讨论】:
-
我写了a lengthy answer about this。不要在应用程序代码中使用
ConfigureAwait(false)。死锁仅在您同步等待异步方法时发生,无论如何您都不应该这样做。
标签: .net asp.net-web-api async-await