Raising an Event between 2 threads when neither th

2019-04-13 09:12发布

问题:

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.

回答1:

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.