我有一个带有文本框和按钮的表单。在点击按钮时,我创建了一个线程,并调用它进行一些操作。一旦线程完成了调用的任务,我想用结果更新文本框。
任何人请帮助我如何才能在没有线程冲突的情况下实现这一点。
发布于 2012-12-23 06:37:36
使用.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();
}发布于 2012-12-23 06:38:16
你需要使用Control.Invoke在它自己的线程中操作你的表单。
发布于 2012-12-23 06:38:44
简单地说,在线程操作的末尾:
/// ... your code here
string newText = ...
textBox.Invoke((MethodInvoker) delegate {
textBox.Text = newText;
});Control.Invoke使用消息队列将工作交给UI线程,因此是UI线程执行textBox.Text = newText;行。
https://stackoverflow.com/questions/14007133
复制相似问题