Search code examples
c#.netwpfmultithreadingdispatcher

correct syntax for using Dispatcher to switch to UI thread


What is the difference between

Dispatcher.CurrentDispatcher.Invoke(somemethod);

and

Application.Current.Dispatcher.Invoke(somemethod);

When I use the first one the execution of somemethod is way faster than the second one.I used stopwatch and measured elapsed milliseconds.I use this method to update some UI controls based on some data coming from external thread.


Solution

  • Dispatcher.CurrentDispatcher will get you dispatcher associated with current thread on which you are invoking this method.

    Whereas Application.Current.Dispatcher will get you dispatcher associated with UI thread (assuming you App is launched from UI thread).


    In essence if you are invoking delegate from background thread and try to update UI component from it say

    textBlock.Text = "Test";
    

    First approach will fail because it will invoke delegate on background thread dispatcher and UI components can only be modified from UI thread.

    Second approach will work because it will delegate task on UI thread.


    When I use the first one the execution of somemethod is way faster than the second one.I used stopwatch and measured elapsed milliseconds.I use this method to update some UI controls based on some data coming from external thread.

    If first approach worked for you then there is no need to use Dispatcher at all because that means you are already on UI thread.

    And you need to post sample data for your observation of timings so it can be validated.