加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 23:49:17 所属栏目:百科 来源:网络整理
导读: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.Wri
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读