相关疑难解决方法(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万
查看次数

isync/await是否适合IO和CPU绑定的方法?

MSDN文档看起来指出asyncawait适合于IO密集型任务,而Task.Run应该用于CPU密集型任务.

我正在处理一个执行HTTP请求以检索HTML文档的应用程序,然后解析它.我有一个看起来像这样的方法:

public async Task<HtmlDocument> LoadPage(Uri address)
{
    using (var httpResponse = await new HttpClient().GetAsync(address)) //IO-bound
    using (var responseContent = httpResponse.Content)
    using (var contentStream = await responseContent.ReadAsStreamAsync())
        return await Task.Run(() => LoadHtmlDocument(contentStream)); //CPU-bound
}
Run Code Online (Sandbox Code Playgroud)

这是好的和适当的使用asyncawait,或者我是否过度使用它?

c# asynchronous async-await c#-5.0

40
推荐指数
3
解决办法
1万
查看次数

在 .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
查看次数