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 :)!
This is accomplished by using either Invoke or BeginInvoke. Invoke is synchronous and BeginInvoke is asynchronous. The operation is added to the event queue of the Dispatcher at the specified DispatcherPriority. Invoke is a synchronous operation; therefore, control will not return to the calling object until after the callback returns.
Invoke (DispatcherPriority, TimeSpan, Delegate, Object, Object []) Executes the specified delegate at the specified priority with the specified arguments synchronously on the thread the Dispatcher is associated with.
To specify an infinite wait, use a value of -1. In a same-thread call, any other negative value is converted to -1, resulting in an infinite wait. In a cross-thread call, any other negative value throws an ArgumentOutOfRangeException. An array of objects to pass as arguments to the given method. Can be null if no arguments are needed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With