2011-03-15 61 views
2

我写在C#一个简单的WinForms应用程序后从工作线程的UI消息。我创建了一个工作线程,我想在主窗口向胎面整理工作作出反应 - 只是改变文本字段,testField.Text =“准备就绪”一些文字。我尝试过事件和回调,但它们都在调用线程的上下文中执行,并且您无法从工作线程执行UI。如何在C#

我知道该怎么做,在C/C++:从工作线程调用PostMessage的。我假设我可以从C#调用Windows API,但没有更具体的.NET特定解决方案吗?

+0

Control.BeginInvoke()是* *确切等效于PostMessage的()。有了额外的优势,您可以选择目标方法并将其传递给您想要的任何参数。 – 2011-03-15 18:58:01

回答

2

在从完成的线程事件回调,使用InvokeRequired模式,通过各种答案,这是证明SO后证明。

C#: Automating the InvokeRequired code pattern

另一种选择是使用BackgroundWorker组件运行的线程。该RunWorkerCompleted执行事件处理程序在启动工作者线程的上下文。

0

的Control.Invoke()或Form.Invoke()方法执行你的UI线程上提供的委托。

1

我常做这样的事情

void eh(Object sender, 
EventArgs e) 
{ 
    if (this.InvokeRequired) 
    { 
     this.Invoke(new EventHandler(this.eh, new object[] { sender,e }); 
     return; 
    } 
    //do normal updates 
} 
0

您可以使用形式的调用函数。该函数将在UI线程上运行。

EX:

... 
MethodInvoker meth = new MethodInvoker(FunctionA); 
form.Invoke(meth); 
.... 

void FunctionA() 
{ 
    testField.Text = "Ready". 
}