我有一个简单的小winforms应用程序,通过TPL任务在另一个线程上执行长时间运行的进程。在这个长时间运行的过程中,我想更新UI(进度条或其他)。有没有办法做到这一点,而不需要.ContinueWith()?如何从WinForms中的子任务更新UI
public partial class Form1 : Form
{
private Task _childTask;
public Form1()
{
InitializeComponent();
Task.Factory.StartNew(() =>
{
// Do some work
Thread.Sleep(1000);
// Update the UI
_childTask.Start();
// Do more work
Thread.Sleep(1000);
});
_childTask = new Task((antecedent) =>
{
Thread.Sleep(2000);
textBox1.Text = "From child task";
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
执行此代码,我得到了无处不在的例外:
Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.
我认为你必须粘贴文本框引用的线程。 – jwillmer 2012-03-12 19:14:23