Search code examples
c#.netwpfmultithreadinginvoke

C# Dispatcher Invoke and normal code execution order


I have some doubts on how Dispatcher.Invoke exactly works. It more of a theoretical question (I don't have any code written in this way).

Let's suppose I have this code:

Application.Current.Dispatcher.Invoke( () => func1() );
func2();
Application.Current.Dispatcher.Invoke( () => func3() );
func4();

From what I have understood, func1() is guaranteed to be executed before func3(). (and func2() before func4()). But what is the relation between the invoked functions (1 and 3) and the normal functions (2 and 4)?

Since the invoked functions are executed on their thread, I suppose that there is not really a relation: for example, func1() might be executed before or after func2(), depending on the thread availability. But I suppose func3() will be executed always after func2(), since it is started after it. I also think that some functions might have overlapped execution, being on different threads.

Is this correct? Or I understood something wrong?


Solution

  • According to the documentation:

    Invoke is a synchronous operation; therefore, control will not return to the calling object until after the callback returns.

    So the func1(), func2(), func3() and func4() methods in your example will be invoked in exactly this order, sequentially and without overlap.