views:

183

answers:

1

Hello all, I would like to know how it is possible that C# Invoke function can work (I am now considering the call from worker thread to invoke a method that manipulates GUI from GUI thread):

Assume I have two threads, and each one of them has it's inctruction pointer, pointing on an instruction that is currently executed.

Now, I call Invoke in worker thread to run a delegate in GUI thread. How is this possible when a GUI thread already has it's instruction pointer (IP), and each thread can only have one? What happens with that IP when I suddenly invoke my code? And how is it made that the GUI thread can afterwards continue with whatever it was doing (is its former IP restored somehow)?

Generalization of this question is, how it is done when I want to call a function f() from thread 1 in a way that f() is executed in a context of some other thread...

Thank you for enlightenment :)!

+6  A: 

It sends a a Window message to the target thread. The thread must be in a message loop for Invoke to work. When the thread gets the message, it calls the delegate.

No cross-thread IP changes are necessary - in fact, changing the IP would almost definitely crash the target thread.

Michael
The answer is correct, but just to be clear, it's a Window Message which is sent, so that when the UI thread message pump runs it will get the message and process it.
Lucero
Actually, the runtime is in some situations able to actively pre-empt the running thread and go do its own thing. I'm not clear on the details; at least one of these involves invoking garbage collection but there may be others.
Promit
Thank to you both - so when the target thread is busy, the method can be invoked only after thread finished processing and started processing the messages. And the means for this is a Windows message with a delegate parameters in some payload.Thanks, I tried to google the answer, but everywhere it was 'Just add Invoke and you'll be fine' tutorials only...
Tomáš Kafka