Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.Factory.StartNew invoked on UI thread anyhow

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

like image 382
christoph Avatar asked Oct 22 '25 15:10

christoph


1 Answers

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

like image 95
christoph Avatar answered Oct 25 '25 09:10

christoph