windows 如何从 C# 中的工作线程发布 UI 消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5316296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to post a UI message from a worker thread in C#
提问by Bartosz Milewski
I'm writing a simple winforms app in C#. I create a worker thread and I want the main window to respond to the tread finishing its work--just change some text in a text field, testField.Text = "Ready". I tried events and callbacks, but they all execute in the context of the calling thread and you can't do UI from a worker thread.
我正在用 C# 编写一个简单的 winforms 应用程序。我创建了一个工作线程,我希望主窗口响应完成其工作的胎面——只需更改文本字段中的一些文本,testField.Text = "Ready"。我尝试了事件和回调,但它们都在调用线程的上下文中执行,您不能从工作线程执行 UI。
I know how to do it in C/C++: call PostMessage from the worker thread. I assume I could just call Windows API from C#, but isn't there a more .NET specific solution?
我知道如何在 C/C++ 中做到这一点:从工作线程调用 PostMessage。我假设我可以从 C# 调用 Windows API,但是没有更多 .NET 特定的解决方案吗?
采纳答案by Matt Davis
In the event callback from the completed thread, use the InvokeRequired
pattern, as demonstrated by the various answers to this SO post demonstrate.
在来自已完成线程的事件回调中,使用该InvokeRequired
模式,如此 SO 帖子演示的各种答案所示。
C#: Automating the InvokeRequired code pattern
Another option would be to use the BackgroundWorker
component to run your thread. The RunWorkerCompleted
event handler executes in the context of the thread that started the worker.
另一种选择是使用该BackgroundWorker
组件来运行您的线程。该RunWorkerCompleted
事件处理程序执行启动该工作者线程的上下文。
回答by madmik3
i normally do something like this
我通常做这样的事情
void eh(Object sender,
EventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(new EventHandler(this.eh, new object[] { sender,e });
return;
}
//do normal updates
}
回答by Kipotlov
You can use the Invoke function of the form. The function will be run on the UI thread.
您可以使用表单的调用函数。该函数将在 UI 线程上运行。
EX :
前任 :
...
MethodInvoker meth = new MethodInvoker(FunctionA);
form.Invoke(meth);
....
void FunctionA()
{
testField.Text = "Ready".
}
回答by Dekryptid
回答by Scott Pedersen
The Control.Invoke() or Form.Invoke() method executes the delegate you provide on the UI thread.
Control.Invoke() 或 Form.Invoke() 方法执行您在 UI 线程上提供的委托。