当两个线程都是WinForm时,在2个线程之间提高事件 [英] Raising an Event between 2 threads when neither thread is a WinForm

查看:169
本文介绍了当两个线程都是WinForm时,在2个线程之间提高事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到ac#示例,显示如何在以下条件下提出跨线程事件:



假设我有1个事件和3个线程:


事件DoStuff



线程A - WinForm



线程B - 从线程A生成的线程进行一些处理。有功能Foo()订阅DoStuff



线程C - 从线程B生成的线程进行一些子处理和提升事件DoStuff


现在我如何确保线程C中提升的事件在线程B而不是C或A内进行处理。



我运行的所有示例都提示使用Form / Control.Invloke,或者某种事情,我真的希望拥有任何Thread实际订阅的内容,而不仅仅是主表单线。

解决方案

将一个线程调用为具体其他线程是非常不平凡的。不可能任意中断线程并执行一些代码。这导致了可怕的重入问题。尝试通过使用信号量来保护这一点,可以保证会导致死锁。



目标线程必须合作,它必须是空闲的,而不是主动地突变状态的程序。一个常见的机制是线程安全的队列。事件提升线程在队列上发出请求,目标线程需要一个循环,读取队列中的请求并执行它们。也许这听起来很熟悉,是的,这是程序的UI线程的工作方式。


I am having trouble finding a c# example that shows how to raise a cross-thread event in the following condition:

Let's say I have 1 Event and 3 Threads:

Event DoStuff

Thread A - WinForm

Thread B - Thread Spawned from Thread A to do some processing. Has Function Foo() which is subscribed to DoStuff

Thread C - Thread Spawned from Thread B to do some subprocessing and Raises event DoStuff

Now How do I ensure that The event Raised in Thread C is processed inside of Thread B instead of C or A.

All of the samples I run accross hint towards Form/Control.Invloke, or somthing of that sort, where I really actually want to have whatever Thread actually subscribed to the event execute inside of it's repsective thread, not just the Main Form Thread.

解决方案

Marshaling a call from one thread to specific other thread is highly untrivial. It is not possible to arbitrarily interrupt the thread and make it execute some code. That causes horrible re-entrancy problems. Trying to protect against that with, say, a semaphore is guaranteed to cause deadlock.

The target thread has to cooperate, it must be 'idle' and not actively mutating the state of the program. A common mechanism for that is a thread-safe queue. The event raising thread puts a request on the queue, the target thread needs a loop that reads the requests off the queue and executes them. Maybe this sounds familiar, yes, that's the way the UI thread of a program works.

这篇关于当两个线程都是WinForm时,在2个线程之间提高事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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