线程之间的C#事件在自己的线程中执行(如何)? [英] C# Events between threads executed in their own thread (How to)?

查看:206
本文介绍了线程之间的C#事件在自己的线程中执行(如何)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有两个线程。让我们称他们为:

I'd like to have two Threads. Let's call them :


  • 线程A

  • 线程B

主题一个触发事件和线程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#事件在自己的线程中执行(如何)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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