zer0ne
zer0ne

Reputation: 423

Dispatcher.Invoke() vs not creating any thread

In a WPF application, what is the difference between calling a method directly vs passing it to Dispatcher.Invoke()? Based on what I have read so far, both are executed in the same UI thread, aren't they?

Sample code

Case 1:

public sealed partial class Window
{ 
    private void SomeEventHandler(object sender, EventArgs e) 
    {
        SomeMethod();
    }
}

Case 2:

public sealed partial class Window
{ 
    private void SomeEventHandler(object sender, EventArgs e) 
    {
        Dispatcher.Invoke(SomeMethod, DispatcherPriority.Send);
    }
}

Upvotes: 0

Views: 187

Answers (2)

Hans Passant
Hans Passant

Reputation: 942255

This question would only be meaningful if the code runs on the UI thread. Clearly there's a huge difference if you call it from a worker thread. And you use Dispatcher.BeginInvoke, not Invoke(). So let's work the "might be useful" angle.

Yes, the delegate target will run on the UI thread in both cases. The difference is in when it runs. When you use Dispatcher.BeginInvoke() then it will not execute until your program goes idle again and re-enters the dispatcher loop. Typically after your current method returns, it depends on how it got activated.

While that sounds rather pointless, it can be useful in certain cases. Useful when the method is activated due to an event and doing something in the event handler is dangerous because of re-entrancy problems. A classic danger is getting the event to fire again, your code will bomb with this web-site's name. Or when code runs after the event fires that undoes what you did in your event handler. Using Dispatcher.BeginInvoke() is a clean way to delay the execution of your event handler code. This otherwise models the way async/await works in C# 5.

Upvotes: 6

makc
makc

Reputation: 2579

you can use UI threads dispatcher from a background thread whenever you need an action to run on the UI thread for example update TextBox.Text

moreover Dispatcher maintains a prioritized queue of work items so you can run an action with different DispatcherPriority for example you would like your action to be performed with Background priority The meaning that the operations are processed after all other non-idle operations are completed.

Upvotes: 1

Related Questions