Reputation: 4853
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 :)!
Upvotes: 10
Views: 2071
Reputation: 55435
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.
Upvotes: 10