如何在C#中的工作线程发布消息的用户界面 [英] How to post a UI message from a worker thread in C#

查看:86
本文介绍了如何在C#中的工作线程发布消息的用户界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写在C#一个简单的WinForms应用程序。我创建了一个工作线程,我想在主窗口向胎面整理工作作出反应 - 只是改变文本字段,testField.Text =就绪一些文字。我试着事件和回调,但他们都在调用线程的上下文中执行,你不能从一个工作线程做UI。

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 / C ++:从工作线程调用PostMessage的。我想我可以从C#调用Windows API,但是是不是有更多的.NET具体的解决方案?

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?

推荐答案

在从完成的线程事件回调,使用 InvokeRequired 格局,由各个答案,这样的表现出来后显示出来。

In the event callback from the completed thread, use the InvokeRequired pattern, as demonstrated by the various answers to this SO post demonstrate.

C#:自动化

另一种选择是使用的BackgroundWorker <的InvokeRequired代码模式/ code>组件运行的线程。在 RunWorkerCompleted 执行事件处理程序在启动工作者线程的上下文。

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.

这篇关于如何在C#中的工作线程发布消息的用户界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆