问题描述
我想要两个线程.让我们称呼他们:
I'd like to have two Threads. Let's call them :
- 线程 A
- 线程 B
线程 A 触发一个事件,线程 B 监听这个事件.当线程B事件监听器执行时,它是用线程A的线程ID执行的,所以我猜它是在线程A内执行的.
Thread A fires an event and thread B listen to this event. When the Thread B Event Listener is executed, it's executed with the Thread A's thread ID, so i guess it is executed within the Thread A.
我想做的是能够向线程 B 触发事件,说如下:嘿,数据已经为你准备好了,你现在可以处理它了".这个事件必须在它自己的线程中执行,因为它使用了只有他才能访问的东西(比如 UI 控件).
What I'd like to do is be able to fire event to Thread B saying something like: "hey, a data is ready for you, you can deal with it now". This event must be executed in its own Thread because it uses things that only him can access (like UI controls).
我该怎么做?
感谢您的帮助.
推荐答案
您需要将信息编组回 UI 线程.
You'll need to marshal the information back into the UI thread.
通常,您将在事件处理程序中处理此问题.例如,假设线程 A 是您的 UI 线程 - 当它订阅线程 B 中对象上的事件时,事件处理程序将在线程 B 内运行.但是,它可以将其封送回 UI 线程:
Typically, you would handle this in your Event handler. For example, say Thread A was your UI thread - when it subscribed to an event on an object in Thread B, the event handler will be run inside Thread B. However, it can then just marshal this back into the UI thread:
// In Thread A (UI) class...
private void myThreadBObject_EventHandler(object sender, EventArgs e)
{
this.button1.BeginInvoke( new Action(
() =>
{
// Put your "work" here, and it will happen on the UI thread...
}));
}
这篇关于在自己的线程中执行的线程之间的 C# 事件(如何)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!