Task.Factory.StartNew invoked on UI thread anyhow

自作多情 提交于 2019-12-12 15:52:21

问题


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.

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

Here my code:

// 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());

Ideas?

Thanks Christoph

EDIT:

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


回答1:


Thank you all for your hints,

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().

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.

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

Christoph



来源:https://stackoverflow.com/questions/17702226/task-factory-startnew-invoked-on-ui-thread-anyhow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!