C#、事件处理程序和线程
我正在编写一个小聊天应用程序,并且有一个事件处理程序:
void o_Typing(object sender, EventArgs e)
{
MessageBox.Show("Fired!");
this.Text = "Fired!";
}
o_Typing
是从 TabPage
派生的类中的一个方法。 基本上,我希望每个对话都有自己的选项卡。
事件处理程序由我的聊天对象触发,该对象在另一个线程中运行。 我有 1 个用于 UI 的线程,还有另一个用于每个聊天对话的线程(以不断轮询服务器以获取新数据)
当事件被触发时,会弹出 MessageBox
,但选项卡标题不会更改。 该事件触发一次后,就再也不会触发,这让我相信该事件是在工作线程中调用的,尽管它是在 UI 线程中定义的。
如何从工作线程调用我的事件,并使用 Invoke()
让它们在 UI 线程上执行?
I'm writing a little chat app, and I have this event handler:
void o_Typing(object sender, EventArgs e)
{
MessageBox.Show("Fired!");
this.Text = "Fired!";
}
o_Typing
is a method in a class derived from TabPage
. Basically, I want each conversation to have it's own tab.
The event handlers are fired by my Chat object, which is running in another thread. I have 1 thread for UI, and another thread for each Chat conversation (to keep polling the server for new data)
When the event is fired, the MessageBox
pops up, but the Tab caption doesn't change. After the event has fired once, it never fires again, leading me to believe that the event is being called in the worker thread, although it is defined in the UI thread.
How can I get my events to be called from the worker thread, and use Invoke()
to get them to execute on the UI thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有两种选择:
1) 使事件处理程序成为线程安全的:在任何需要与 UI 线程通信的事件处理程序中使用 Control.Invoke/BeginInvoke。
2) 在引发事件之前让工作线程封送回 UI 线程 - 换句话说,使用
Control.Invoke
作为引发事件过程的一部分,以便事件处理程序都将被在 UI 线程中调用。 根据应用程序的结构,您可能不希望事件引发组件显式了解 UI - 但在构建它时,您可以传入ISynchronizeInvoke
(其中Control
code>implements) 并且您的组件可以使用它在正确的线程上引发其事件。 当然,只有当每个事件处理程序都乐意在同一个线程上运行时,这才有效(简单地说,无论如何)——但情况往往如此。 你会写这样的东西:There are two options:
1) Make the event handlers thread-safe: use
Control.Invoke/BeginInvoke
in any event handler which needs to talk to the UI thread.2) Make the worker thread marshal back to the UI thread before raising the event - in other words, use
Control.Invoke
as part of the process of raising the event, so that the event handlers will all be called in the UI thread. Depending on how your app is structured, you may not want your event-raising component to know about the UI explicitly - but when it's being constructed you can pass in anISynchronizeInvoke
(whichControl
implements) and your component can use that to raise its events on the right thread. Of course, that only works (simply, anyway) if every event handler is happy to run on the same thread - but that will often be the case. You'd write something like:如果您在工作线程执行的代码中触发事件,则订阅该事件的所有方法都将在该工作线程下执行。
对于 GUI 元素,您需要查看调用方法。
此致
If you fire your event in code which is executed by your worker thread, then all methods subscribed to the event will be executed under that worker thread.
For GUI-elements you need to look at the Invoke-methods.
Best Regards