Task.Run not running in background but on Dispatcher

Joe

I have one of my CPU intensive tasks blocking the UI thread, after investigating I've found that the root of the problem seems to be the Task.Run actually running in the Dispatcher thread:

Task.Run(() =>
{
    if (Dispatcher.CurrentDispatcher.Thread == Thread.CurrentThread)
    {
        // breakpoint
    }
});

Placing a breakpoints in the if statement is hit.

Is this expected behaviour? I understood Task.Run to use a different thread.

mm8

The action that you pass to Task.Run is executed on a thread pool thread if you use the default task scheduler (which you are by default).

This should give you the expected result:

Task.Run(() =>
{
    if (System.Windows.Application.Current.Dispatcher.Thread == Thread.CurrentThread)
    {
        // breakpoint not hit in WPF...
    }
});

There is a difference between System.Windows.Application.Current.Dispatcher and System.Windows.Threading.Dispatcher.CurrentDispatcher:

Dispatcher.CurrentDispatcher vs. Application.Current.Dispatcher

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related