await
does not guarantee continuation on the same task for spawned tasks:
private void TestButton_Click(object sender, RoutedEventArgs e)
{
Task.Run(async () =>
{
Debug.WriteLine("running on task " + Task.CurrentId);
await Task.Delay(TimeSpan.FromMilliseconds(100));
Debug.WriteLine("running on task " + Task.CurrentId);
});
}
The output of this is:
running on task 1
running on task
so we can see that not only the execution has moved to another task, but also to the UI-thread. How can i create a dedicated task, and enforce await to always continue on this task? Long-running tasks don't do this either.
I have seen several SynchronizationContext implementations, but so far none of them worked, in this case because it uses threads and System.Threading.Thread is not available for uwp.
No, it's not on the UI thread. It's just technically not on a task, either. I explain why this happens in my blog post on
Task.CurrentId
inasync
methods.You're on the right track: you need a custom
SynchronizationContext
(or a customTaskScheduler
).Try out mine. It should work on UWP 10.0.
Don't use
Task.Run
, just make the event handler asyncRead more about
Task.CurrentId
in Async Methods here:Reply to comments
The case with a thread pool thread is included in the link. In particular look at this example
Again, the clarification is
This is an implementation detail of the
async
call, I can only quote the link again:So you can't and you should not stop it from doing that, as far as a truly
async
call is concerned.What you describe as the expected behavior instead is equivalent to a
Task.Run
withoutawait
Or a nested
Task.Run
Output