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.
LongRunning
is merely a hint to the TaskScheduler
. In the case of the SynchronizationContextTaskScheduler
(as returned by TaskScheduler.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:
LongRunning - Specifies that a task will be a long-running, coarse-grained operation. It provides a hint to the TaskScheduler that oversubscription may be warranted.
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:
void ShortUIWork()
{
Debug.Assert(this.Dispatcher.CheckAccess() == true);
Task.Factory.StartNew(LongWork, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}