请考虑以下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)有用吗?
MSDN文档看起来指出async并await适合于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)
这是好的和适当的使用async和await,或者我是否过度使用它?
我在很多地方都读过 ConfigureAwait(包括 SO 问题),以下是我的结论:
.ConfigureAwait(true). 否则,由于另一个线程访问 UI 元素,将发生 InvalidOperationException。我的问题是: