Emanuele
Emanuele

Reputation: 56

When the code inside Dispatcher.Invoke is executed?

In a C# WPF project I have a background thread that needs to refresh some UserControls. To doing that I used the Dispatcher.Invoke:

    Dispatcher.Invoke(DispatcherPriority.Normal, (MethodInvoker)delegate()
    {
        // Code
    }

But I'm wondering:

Thanks a lot, Emanuele

Upvotes: 1

Views: 1037

Answers (2)

Rohit Vats
Rohit Vats

Reputation: 81233

when the code inside the delegate will be executed on the main thread?

Delegate will execute on main thread once if all the operations with priority greater than Normal got a chance to execute.

To execute it, a method normally running on main thread could be stopped?

Invoke method make the delegate to execute synchronously on Main thread but if you want to execute it asynchronously, you need to use BeginInvoke. In case some delegate is running on Main thread, your delegate will get queued and will run once executing operation gets completed. However, your background thread won't move forward unless delegate gets executed.

Could the use of Dispatcher.Invoke lead to race conditions?

No, it won't since delegate gets queued in Dispatcher Queue.

Upvotes: 3

AgentFire
AgentFire

Reputation: 9780

  1. Exactly when the UI thread is able to switch its execution on SynchronizationContext.Send call.
  2. When executing it, the method which is normally being run on main thread will finish running (including other pseudo non-finish conditions like yield or await) and then your function will be ran.
  3. No.

Upvotes: 0

Related Questions