相关疑难解决方法(0)

为什么我懒得使用Task.ConfigureAwait(continueOnCapturedContext:false);

请考虑以下Windows窗体代码:

private async void UpdateUIControlClicked(object sender, EventArgs e)
    {
        this.txtUIControl.Text = "I will be updated after 2nd await - i hope!";
        await Task.Delay(5000).ConfigureAwait(continueOnCapturedContext: false);
        this.txtUIControl.Text = "I am updated now.";
    }
Run Code Online (Sandbox Code Playgroud)

这里异常是在第3行引发的,因为在等待代码在非UI线程上执行之后.ConfigureAwait(false)有用吗?

c# synchronizationcontext async-await

59
推荐指数
2
解决办法
4万
查看次数

在 .NET 中使用 ConfigureAwait

我在很多地方都读过 ConfigureAwait(包括 SO 问题),以下是我的结论:

  • ConfigureAwait(true):在与运行 await 之前的代码相同的线程上运行其余代码。
  • ConfigureAwait(false):在运行等待代码的同一线程上运行其余代码。
  • 如果 await 后跟访问 UI 的代码,则任务应附加.ConfigureAwait(true). 否则,由于另一个线程访问 UI 元素,将发生 InvalidOperationException。

我的问题是:

  1. 我的结论正确吗?
  2. ConfigureAwait(false) 什么时候可以提高性能,什么时候不能?
  3. 如果为 GUI 应用程序编写,但下一行不访问 UI 元素。我应该使用 ConfigureAwait(false) 还是 ConfigureAwait(true) ?

.net c# asynchronous async-await configureawait

6
推荐指数
1
解决办法
3314
查看次数

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

我正在检查一些使用 .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);
      }
  }
Run Code Online (Sandbox Code Playgroud)

我读到,最佳实践是不在ConfigureAwait应用程序代码中使用,以便继续执行捕获的同步上下文,因为可能存在与捕获的上下文关联的所需状态。然而,一般来说,我们应该使用ConfigureAwait(false)这样的方法,这样我们就不会不必要地继续捕获的同步上下文。

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

然后我读到了有关死锁的内容,并且在使用 ASP.NET Core 时这并不重要(尽管我不是)。

我添加了一个断点并检查了SynchronizationContext.Current哪个是null.

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

.net async-await asp.net-web-api

2
推荐指数
1
解决办法
612
查看次数