c# – 我如何强制等待在同一个线程上继续?

await不保证在生成任务的同一任务上继续:

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);
    });
}

这个输出是:

running on task 1
running on task

所以我们可以看到,不仅执行已经移动到另一个任务,而且还移动到UI线程.如何创建专用任务,并强制等待始终继续执行此任务?长时间运行的任务也不会这样做.

我已经看过几个SynchronizationContext implementations,但到目前为止它们都没有工作,在这种情况下,因为它使用线程和System.Threading.Thread不适用于uwp.

最佳答案

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

不,它不在UI线程上.从技术上讲,这也不是一项任务.我在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.

你走在正确的轨道上:你需要一个自定义的SynchronizationContext(或一个自定义的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.

试试mine.它应该适用于UWP 10.0.

转载注明原文:c# – 我如何强制等待在同一个线程上继续? - 代码日志