The following code is a simplification of a code in a real application. The problem below is that a long work will be ran in the UI thread, instead of a background thread.
void Do()
{
Debug.Assert(this.Dispatcher.CheckAccess() == true);
Task.Factory.StartNew(ShortUIWork, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
}
void ShortUIWork()
{
Debug.Assert(this.Dispatcher.CheckAccess() == true);
Task.Factory.StartNew(LongWork, TaskCreationOptions.LongRunning);
}
void LongWork()
{
Debug.Assert(this.Dispatcher.CheckAccess() == false);
Thread.Sleep(1000);
}
So Do() is called normally from UI context. And so is ShortUIWork, as defined by the TaskScheduler. However, LongWork ends up called also in UI thread, which, of course, blocks the UI.
How to ensure that a task is not ran in the UI thread?
LongRunningis merely a hint to theTaskScheduler. In the case of theSynchronizationContextTaskScheduler(as returned byTaskScheduler.FromCurrentSynchronizationContext()), it apparently ignores the hint.On the one hand this seems counterintuitive. After all, if the task is long running, it’s unlikely you want it to run on the UI thread. On the other hand, according to MSDN:
Since the UI thread isn’t a thread pool thread, no “oversubscription” (thread pool starvation) can occur, so it somewhat makes sense that the hint will have no effect for the
SynchronizationContextTaskScheduler.Regardless, you can work around the issue by switching back to the default task scheduler: