Tech Off Thread

6 posts

Nested Task.Factory.StartNew() creates the task on the UI thread

Back to Forum: Tech Off
  • User profile image
    BitFlipper

    I have some code that uses Task.Factory.StartNew() to start a background task when the user clicks a button. Upon completion, the background task then calls Task.Factory.StartNew() but specifies the UI thread context in order to update the UI with the results.

    This work fine. However now I have a UI option that will allow the task to run repeatedly until the user cancels it. So now in the second Task.Factory.StartNew() that runs the task on the UI thread, I just call the first function that starts the background task again. However what I'm finding is that the second time around, the first Task.Factory.StartNew() runs the task on the UI thread even though I did not pass in a thread context to it. I'm not sure it matters, but I'm passing in TaskCreationOptions.LongRunning as well for both calls.

    To put it another way... In both cases the first Task.Factory.StartNew() was called from the UI thread. The 1st time, it runs the task on a background thread. The second time, on the UI thread. Exact same code and parameters.

    Any ideas why this would be happening?

  • User profile image
    BitFlipper

    Looks like I'm running into this problem. However I'm not using the ContinueWith call, so I'm not sure how to fix my issue. I'm essentially making a nested call to Task.Factory.StartNew().

  • User profile image
    BitFlipper

    OK I solved the problem by passing in TaskScheduler.Default into the 2nd [fixed it] Task.Factory.StartNew() call.

  • User profile image
    JohnAskew

    [TaskScheduler.Default] puts the first thread at a known location so that it can be found for the next thread evoked? How does it work?

  • User profile image
    BitFlipper

    , JohnAskew wrote

    [TaskScheduler.Default] puts the first thread at a known location so that it can be found for the next thread evoked? How does it work?

    I have no idea. But it fixed my issue.

  • User profile image
    BitFlipper

    , BitFlipper wrote

    *snip*

    I have no idea. But it fixed my issue.

    Ah you are correct. Sorry that was a typo. I'm passing TaskScheduler.Default into the 2nd call.

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.