可以在UI线程上调用Task.Factory.StartNew [英] Task.Factory.StartNew invoked on UI thread anyhow

查看:123
本文介绍了可以在UI线程上调用Task.Factory.StartNew的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

至少从我的角度来看,我必须处理一个奇怪的问题.我使用Task来等待,直到变量获得特定值,然后再次在ui线程上运行Continue部分.

I have to deal with a strange problem, at least from my point of view. I use a Task to wait untill a variable gets a specific value and then run the Continue part on the ui thread again.

现在的问题是,在调用StartNew()之前和在调用内部,ManagedThreadId相同,并且冻结了UI.

Problem now is that before I call StartNew() and inside the call the ManagedThreadId is the same and it freezes my UI.

这是我的代码:

// ManagedThreadId here
Task.Factory.StartNew(() => 
{
    // and here are the same.
    while (isClosing)
    {
        Thread.Sleep(50);
    }
}).ContinueWith((finishedTask) => 
{
    if (currentContainer != null)
    {
        window = currentContainer;
    }
    else
    {
         window = CreateBallonWindow();
         window.Show();
    }

    window.Activate();
}, TaskScheduler.FromCurrentSynchronizationContext());

想法?

感谢克里斯托夫

对我来说最有趣的是为什么发生这种情况而不是如何解决此问题. 我想了解那里发生了什么...

Most interesting for me is why this happens not how to get around this issue. I want to understand what happens there...

推荐答案

谢谢大家的提示,

我终于以为我明白了.这里的问题是TaskScheduler.Current是调用StartNew()时使用的默认调度程序.使用TaskScheduler.SynchronizationContext()时,这不是一个很好的组合.

I finally think that I got it. The problem here is that TaskScheduler.Current is the default scheduler used when calling StartNew() . And this is no good combination when using TaskScheduler.SynchronizationContext().

这里的情况是,我(通过TaskScheduler.SynchronizationContext()描述的调度程序)在连续任务中(间接)使用了StartNew().因此,默认的调度程序是包含ui线程的调度程序->在ui线程上调用了新Task.

The case here was that I (indirectly) used StartNew() in the continuing task with the scheduler described by TaskScheduler.SynchronizationContext(). So that the default scheduler was the one which contains the ui thread --> the new Task got invoked on the ui thread.

特别感谢Viv分享了链接.它有助于了解发生了什么.

Special thanks to Viv, for sharing the link. It helped a lot to understand what was going on.

Christoph

Christoph

这篇关于可以在UI线程上调用Task.Factory.StartNew的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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