将事件发送到特定线程 [英] Sending Events to a specific Thread

查看:106
本文介绍了将事件发送到特定线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我希望线程处理一些顺序逻辑.该线程有时需要与主线程进行交互,以便更新用户输入.但是它应该继续运行,否则不会打扰主线程.我希望以事件驱动的方式执行此操作,以便主线程不必为中断而占用另一个线程.做这个的最好方式是什么?有没有一种事件驱动技术可以像MFC中一样在线程之间进行通信?

I have a situation in which I want a thread to process some sequential logic. This thread would need to interact with the main thread on occasion in order to update user input. But it should continue running otherwise without bothering the main thread. I am hopping to do this in an event-driven manner, so that the main thread doesn't have to pole the other thread for interrupts. What is the best way to do this? Is there an event-driven technique to communicating between threads much like there is in MFC?

我正在使用Visual Studio 2008和(显然).Net 3.5框架.

I am using Visual Studio 2008 and (obviously) the .Net 3.5 framework.

推荐答案

啊哈!有一种事件驱动的方法可以做到这一点.我从WPF借了Dispatcher.我只允许旋转线程访问主线程的CurrentDispatcher我让线程旋转,当需要注意时,它调用Dispatcher上的委托并休眠以等待主线程中断它.我知道我可以使用Invoke代替BeginInvoke,但是我需要使用中断,因为重新启动工作线程的方法不是分派的委托堆栈的同步部分.

Ah ha! there is an event-driven way to do it. I borrowed the Dispatcher from WPF. I just give the spinning thread access to the main thread's CurrentDispatcher I let the thread spin and when it needs attention it invokes a delegate on the Dispatcher and sleeps waiting for the main thread to interrupt it. I know I could use Invoke instead of BeginInvoke, but I needed to use the interrupt because the method that restarts the worker thread is not a synchronous part of the dispatched delegates stack.

无论好坏,这是我的代码:

For better or worse, here is my code:

private void Run()
{
    while (true)
    {

        ... 

        // Need attention from the main thread
        // "_main" is the main thread's Dispatcher instance.
        _main.BeginInvoke(new MyEventHandler(OnNeedsAttention), this, new MyEventArgs(...));
        try
        {
            Thread.Sleep(Timeout.Infinite);
        }
        catch (ThreadInterruptedException) { }
    }
}

这篇关于将事件发送到特定线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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