[英]C#/WPF Using async and await but the UI thread is still blocked
我有这个简单的代码:
private async void Button_Click_2(object sender, RoutedEventArgs e)
{
var progress = new Progress<int>();
progress.ProgressChanged += (a, b) =>
{
this.progressBar.Value = b;
};
// this is blocking
await this.LongRunOpAsync(filepath, progress);
// this is not blocking
// await this.LongRunOpAsync(filepath, null);
}
public Task LongRunOpAsync(string filename, IProgress<int> progress)
{
return Task.Run(() =>
{
using (var ops = new LongOps())
{
ops.LongRunOp(filename, progress);
}
});
}
单击按钮后,UI仍然无法进行长时间运行。 如果我不使用Progress,而是将长时间运行的操作设为null作为第二个参数,则UI不会阻塞。 我非常确定这个“错误”是由于我对异步/等待和线程有一些误解造成的。
您显示的代码不会阻塞UI线程。
实际上,如图所示,它不需要异步/等待-因此我假设这不是实际的代码。
您需要查看ops.LongRunOp
对progress
函数的作用。
我怀疑它封送了回到UI线程的progress
-因此它可以访问UI控件。
如果这样做太频繁和太快,它将淹没UI线程并使应用程序无响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.