2012-12-22 55 views
2

我有一個帶有文本框和按鈕的窗體。點擊按鈕我創建一個線程並調用它進行一些操作。一旦線程完成調用的任務,我想用結果更新文本框。線程通訊

任何人請幫助我,我怎麼能實現這一點,沒有線程衝突。

回答

3

這是更簡單使用.NET 4.0的Task類:

private void button_Click(object sender, EventArgs e) 
{ 
    Task.Factory.StartNew(() => 
    { 
     return DoSomeOperation(); 
    }).ContinueWith(t => 
    { 
     var result = t.Result; 
     this.textBox.Text = result.ToString(); // Set your text box 
    }, TaskScheduler.FromCurrentSynchronizationContext()); 
} 

如果您使用.NET 4.5,您可以簡化這個進一步使用新的異步支持:

private async void button_Click(object sender, EventArgs e) 
{ 
    var result = await Task.Run(() => 
    { 
     // This runs on a ThreadPool thread 
     return DoSomeOperation(); 
    }); 

    this.textBox.Text = result.ToString(); 
} 
+2

好吧,我會打電話給*「可疑」*「簡單」。它*可能會更簡單,如果你只是使用'await',默認情況下,IIRC使用sync-context –

+0

@MarcGravell我覺得這比調用調用的線程簡單得多,但這是個人偏好。等待的好點 - 我也會把它添加爲一個選項。 –

0

簡單地說,在螺紋操作結束:

/// ... your code here 
string newText = ... 

textBox.Invoke((MethodInvoker) delegate { 
    textBox.Text = newText; 
}); 

Control.Invoke用法使用消息隊列中,以手工作到UI線程,所以它是執行textBox.Text = newText;線UI線程。

0

使用BackgroundWorker,將任務分配給DoWork事件,並使用RunWorkerCompleted事件更新文本框。然後你可以用RunWorkerAsync()開始任務。