我该如何强制在同一线程上继续? [英] how can i force await to continue on the same thread?

查看:106
本文介绍了我该如何强制在同一线程上继续?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

await不保证对衍生任务执行同一任务:

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

此输出为:

running on task 1
running on task

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

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.

推荐答案

因此我们可以看到不仅执行已移至另一个任务,而且移至UI线程.

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

否,它不在UI线程上.从技术上讲,这也不是一项任务.我在 Task.CurrentId中的async方法.

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.

您步入正轨:您需要自定义SynchronizationContext(或自定义TaskScheduler).

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

我已经看到了几种SynchronizationContext实现,但是到目前为止,它们都没有起作用,在这种情况下,因为它使用了线程,而System.Threading.Thread对于uwp不可用.

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.

尝试我的.它应该适用于UWP 10.0.

Try out mine. It should work on UWP 10.0.

这篇关于我该如何强制在同一线程上继续?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆