2

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.

Community
  • 1
  • 1
deepee1
  • 12,878
  • 4
  • 30
  • 43
  • Why are you using an event instead of just joining or using the worker thread pool? – JohnOpincar Jan 31 '11 at 17:10
  • Threads don't handle events, methods do. Maybe explain what you need this for and someone can come up with an alternative. – H H Jan 31 '11 at 17:23
  • I was building a class that may or may not be used in a WinForm (console app perhaps) that spawned a thread. In that thread I wanted to raise an event that would appear to come from the thread that instantiated the class. I just took a more generic approach to the question to see if somehow the subscriptions to the events were aware of which threads the subscriptions came from and if there was some way I was unaware of to execute the subscribed delegate in the original thread. After Hans' response it makes perfect sense why without a message pumping thread this is not reasonable. – deepee1 Feb 03 '11 at 19:59

1 Answers1

4

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536