Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Invoke work underneath? Doesn't thread have only 1 instruction pointer?

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 :)!

like image 780
Tomáš Kafka Avatar asked Apr 20 '09 23:04

Tomáš Kafka


People also ask

What is the difference between begininvoke and invoke?

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.

What does invoke () method do in Apache dispatch?

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.

How to specify an infinite wait in a thread?

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.


1 Answers

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.

like image 69
Michael Avatar answered Oct 05 '22 23:10

Michael