c# - 在没有任务的情况下更新 UI 线程以继续
问题描述
我目前有一个启动方法并循环给定次数的任务。每个循环我都想模拟一些正在完成的工作(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 工作?提前致谢。
解决方案
您可以使用IProgress<T>
将进度报告回 UI 线程。
private void StartButton_Click(object sender, RoutedEventArgs e)
{
this.pbStatus.Value = 0;
//Setup the progress reporting
var progress = new Progress<int>(i =>
{
this.lblOutput.Text = i.ToString();
this.pbStatus.Value = i;
});
Task.Run(() => StartProcess(100, progress));
//Show message box to demonstrate that StartProcess()
//is running asynchronously
MessageBox.Show("Called after async process started.");
}
// Called Asynchronously
private void StartProcess(int max, IProgress<int> progress)
{
for (int i = 0; i <= max; i++)
{
//Do some work
Thread.Sleep(10);
//Report your progress
progress.Report(i);
}
}
推荐阅读
- android - 如何通过单击第一个片段的按钮将消息从一个片段发送到另一个片段?
- python - 如何从csv文件中读取前两列
- javascript - 解构扩展的 javascript 参数
- java - 在java中用于嵌套函数的编码实践
- r - 尝试在 R 中抓取 PDF,我的代码只会抓取 9 页中的 6 页,我不知道为什么,我的代码中是否遗漏了什么?
- c# - 清除文本框值
- vb.net - 完成执行任务“RdlCompile”——Visual Studio 2015 中的 FAILED 错误
- php - Laravel 5.6 http://127.0.0.1:8000/ 重定向到 https://127.0.0.1:8000/login (https)
- android - 如何在将用户带到下一个选项卡之前处理 TabLayout 单击?
- git - Git 复制文件到服务器