【发布时间】:2018-11-13 18:42:48
【问题描述】:
我目前有一个启动方法并循环给定次数的任务。每个循环我都想模拟一些正在完成的工作(Thread.Sleep),然后更新 UI。我目前知道更新 UI 线程的唯一方法是任务继续。我的问题是,在方法中,我没有要继续的任务。
private void StartButton_Click(object sender, RoutedEventArgs e)
{
this.pbStatus.Value = 0;
Task.Run(() => StartProcess(100));
//Show message box to demonstrate that StartProcess()
//is running asynchronously
MessageBox.Show("Called after async process started.");
}
// Called Asynchronously
private void StartProcess(int max)
{
for (int i = 0; i <= max; i++)
{
//Do some work
Thread.Sleep(10);
//How to correctly update UI?
this.lblOutput.Text = i.ToString();
this.pbStatus.Value = i;
}
}
有没有办法重构此代码以仅使用 TPL 工作?提前致谢。
【问题讨论】:
标签: c# multithreading task-parallel-library