Reputation: 1035
please take a look at the following code:
So, I grab the current context (WinForms thread), start a new task with that context, and attach a synchonous continuation with the Default
task scheduler. As far as I understand, a continuation should start on a threadpool thread. UI thread doesn't belong to threadpool. But instead, all code including a continuation, is running synchonously on the same thread. That's quite unexpected for me.
Btw, if I set the continuation options as TaskContinuationOptions.None
, it's run on another thread as it should. Seems like continuation options make preference over task scheduler, despite they are just hints and scheduler is a requirement.
TaskScheduler uiContext = TaskScheduler.FromCurrentSynchronizationContext();
Console.WriteLine("start thread {0}", Thread.CurrentThread.ManagedThreadId);
Task.Factory.StartNew(() =>
{
Console.WriteLine("ui thread {0}", Thread.CurrentThread.ManagedThreadId);
}, CancellationToken.None, TaskCreationOptions.None, uiContext).ContinueWith(t =>
{
Console.WriteLine("continuation thread {0}", Thread.CurrentThread.ManagedThreadId);
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
Is it a bug or expected behaviour?
What can I do to guaranteed run of the continuation code outside of UI thread independently of the parent task context and continuation options? Some custom task scheduler?
A note: I know this is a legacy code now, and async/await is the way to go.
Upvotes: 1
Views: 68