Task.Run和UI最新进展 [英] Task.Run and UI Progress Updates
本文介绍了Task.Run和UI最新进展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码来自斯蒂芬·克利里的博客一>,并给出了如何使用Task.Run时,报告进度的例子。我想知道为什么会出现与更新UI,我指的是为什么没有则启动不需要跨线程问题?
专用异步无效button2_Click(对象发件人,EventArgs五)
{
变种progressHandler =新进展<字符串>(价值=>
{
label2.Text =价值;
});
VAR进度= progressHandler作为IProgress<字符串取代;
等待Task.Run(()=>
{
的for(int i = 0;!我= 100; ++ I)
{
如果( !进展=空)
progress.Report(阶段+ I);
Thread.sleep代码(100);
}
});
label2.Text =已完成。
}
解决方案
进展< T>
捕捉当前 SynchronisationContext
当它被实例化。每当你叫报告
,偷偷代表们将捕获的上下文。在该示例中,所捕获的上下文是用户界面中,这意味着没有发生异常。
This code snippet is from Stephen Cleary's blog and gives an example of how to report progress when using Task.Run. I would like to know why there are no cross thread issues with updating the UI, by which I mean why is invoke not required?
private async void button2_Click(object sender, EventArgs e)
{
var progressHandler = new Progress<string>(value =>
{
label2.Text = value;
});
var progress = progressHandler as IProgress<string>;
await Task.Run(() =>
{
for (int i = 0; i != 100; ++i)
{
if (progress != null)
progress.Report("Stage " + i);
Thread.Sleep(100);
}
});
label2.Text = "Completed.";
}
解决方案
Progress<T>
catches the current SynchronisationContext
when it is instantiated. Whenever you call Report
, it secretly delegates that to the captured context. In the example, the captured context is the UI, meaning that no exceptions occur.
这篇关于Task.Run和UI最新进展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文