我有一個簡單的小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