Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6534427
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T10:14:58+00:00 2026-05-25T10:14:58+00:00

Here is some easy piece of code to show the unexpected behavior: public partial

  • 0

Here is some easy piece of code to show the unexpected behavior:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        _UI = TaskScheduler.FromCurrentSynchronizationContext();
        Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }

    TaskScheduler _UI;

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        Task.Factory.StartNew(() =>
        {
            //Expected: Worker thread
            //Found: Worker thread
            DoSomething();
        })
        .ContinueWith(t =>
            {
                //Expected: Main thread
                //Found: Main thread
                DoSomething();

                Task.Factory.StartNew(() =>
                {
                    //Expected: Worker thread
                    //Found: Main thread!!!
                    DoSomething();
                });
            }, _UI);
    }

    void DoSomething()
    {
        Debug.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());
    }
}

Why is the inner task executed in the main thread?
How can i prevent this behavior?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T10:14:58+00:00Added an answer on May 25, 2026 at 10:14 am

    Unfortunately, the Current task scheduler, when you’re running your continuation, becomes the SynchronizationContextTaskScheduler setup by your TaskScheduler.FromCurrentSynchronizationContext.

    This is discussed in this Connect Bug – and was written this way by design in .NET 4. However, I agree that the behavior leaves a bit to be desired here.

    You can work around this by grabbing a “background” scheduler in your constructor, and using it:

    TaskScheduler _UI;
    
    // Store the default scheduler up front
    TaskScheduler _backgroundScheduler = TaskScheduler.Default; 
    
    public MainWindow()
    {
        InitializeComponent();
    
        _UI = TaskScheduler.FromCurrentSynchronizationContext();
        Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }
    

    Once you have that, you can easily schedule your “background” task appropriately:

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        Task.Factory.StartNew(() =>
        {
            //Expected: Worker thread
            //Found: Worker thread
            DoSomething();
        })
        .ContinueWith(t =>
            {
                //Expected: Main thread
                //Found: Main thread
                DoSomething();
    
                // Use the _backgroundScheduler here
                Task.Factory.StartNew(() =>
                {
                    DoSomething();
                }, CancellationToken.None, TaskCreationOptions.None, _backgroundScheduler);
    
            }, _UI);
    }
    

    Also, in this case, since your operation is at the end, you could just put it in its own continuation and get the behavior you want. This, however, is not a “general purpose” solution, but works in this case:

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        Task.Factory.StartNew(() =>
        {
            //Expected: Worker thread
            //Found: Worker thread
            DoSomething();
        })
        .ContinueWith(t =>
            {
                //Expected: Main thread
                //Found: Main thread
                DoSomething();
    
            }, _UI)
        .ContinueWith(t =>
                {
                    //Expected: Worker thread
                    //Found: Is now worker thread
                    DoSomething();
                });
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Here is some code I could not get to format properly in markdown, this
Here's some Ruby code: puts %x{ pstree #{$$} } # never forks puts %x{
Here's some code I saw once. Can you see what's wrong with it? [updated]
Here is some simple code: DIR* pd = opendir(xxxx); struct dirent *cur; while (cur
Here's some code (full program follows later in the question): template <typename T> T
I'm looking for some style advice for testing this piece of (Objective-)C++ code, I
Ok, here are some easy points. PyBinding came with this script: def IsNotNull(value): return
Here's some easy reputation for someone. The scenario I have a table that is
Here is some simple Perl to count the number of times a value occurs
Here's some background on what I'm trying to do: Open a serial port from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.