In the article here, Stephen describes that in the outer StartNew (see code snippet below), TaskScheduler.Current is our UI task scheduler. Indeed, the output of the code below seems to indicate that all is executed on the UI thread. However when I try to confirm this, I get a different answer:
private void Button_Click(object sender, RoutedEventArgs e)
{
var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
var ui = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
ui.StartNew(() =>
{
Debug.WriteLine("TaskScheduler.Current == UI TaskScheduler: " + (uiTaskScheduler == TaskScheduler.Current));
Debug.WriteLine("UI on thread " + Environment.CurrentManagedThreadId);
Task.Factory.StartNew(() =>
{
Debug.WriteLine("Background work on thread " + Environment.CurrentManagedThreadId);
});
});
}
And the output:
TaskScheduler.Current == UI TaskScheduler: False
UI on thread 1
Background work on thread 1
Why exactly does uiTaskScheduler == TaskScheduler.Current
return false?