基本上我想更新 FormMain (WindowsForm) 上的 ProgressBar UI 对象。我正在使用 .NET 4.0
这是 Form1.Designer.cs 中的代码
namespace ProgressBarApp
{
public partial class Form1 : Form
{
private System.Windows.Forms.ProgressBar curProgressBar;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CustomProcess theProcess = new CustomProcess();
theProcess.Process();
}
}
}
这里是 CustomProcess.cs 的定义
namespace ProgressBarApp
{
class CustomProcess
{
public void Process()
{
for (int i = 0; i < 10; i++)
{
Task ProcessATask = Task.Factory.StartNew(() =>
{
Thread.Sleep(1000); // simulating a process
}
);
Task UpdateProgressBar = ProcessATask.ContinueWith((antecedent) =>
{
// how do i update the progress bar object at UI here ?
}
);
}
}
}
}
最佳答案
您可以使用 SynchronizationContext
去做这个。要将它用于Task
,您需要创建一个TaskScheduler
,您可以通过调用TaskScheduler.FromCurrentSynchronizationContext
来完成。 :
Task UpdateProgressBar = ProcessATask.ContinueWith(antecedent =>
{
// you can update the progress bar object here
}, TaskScheduler.FromCurrentSynchronizationContext());
只有当您直接从 UI 线程调用 Process()
时,这才会起作用。
关于c# - 从任务并行库更新 ProgressBar UI 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13946839/