Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

c# - how can i force await to continue on the same thread?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

so we can see that not only the execution has moved to another task, but also to the UI-thread.

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 in async methods.

How can i create a dedicated task, and enforce await to always continue on this task? Long-running tasks don't do this either.

You're on the right track: you need a custom SynchronizationContext (or a custom TaskScheduler).

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.

Try out mine. It should work on UWP 10.0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...