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

  • Home
  • SEARCH
  • 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 8307495
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T18:32:08+00:00 2026-06-08T18:32:08+00:00

I’ve been trying to track down the following issue in a Winforms application: The

  • 0

I’ve been trying to track down the following issue in a Winforms application:
The SynchronizationContext.Current is null in a task’s continuation (i.e. .ContinueWith) which is run on the main thread (I expect the the current synchronization context to be System.Windows.Forms.WindowsFormsSynchronizationContext).

Here’s the Winforms code demonstrating the issue:

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            TaskScheduler ts = TaskScheduler.FromCurrentSynchronizationContext(); // Get the UI task scheduler

            // This line is required to see the issue (Removing this causes the problem to go away), since it changes the codeflow in 
            // \SymbolCache\src\source\.NET\4\DEVDIV_TFS\Dev10\Releases\RTMRel\ndp\clr\src\BCL\System\Threading\ExecutionContext.cs\1305376\ExecutionContext.cs
            // at line 435
            System.Diagnostics.Trace.CorrelationManager.StartLogicalOperation("LogicalOperation");

            var task = Task.Factory.StartNew(() => { });
            var cont = task.ContinueWith(MyContinueWith, CancellationToken.None, TaskContinuationOptions.None, ts);

            System.Diagnostics.Trace.CorrelationManager.StopLogicalOperation();
        }

        void MyContinueWith(Task t)
        {
            if (SynchronizationContext.Current == null) // The current SynchronizationContext shouldn't be null here, but it is.
                MessageBox.Show("SynchronizationContext.Current is null");
        }
    }
}

This is an issue for me since I attempt to use BackgroundWorker from the continuation, and the BackgroundWorker will use the current SynchronizationContext for its events RunWorkerCompleted and ProgressChanged. Since the current SynchronizationContext is null when I kick off the BackgroundWorker, the events don’t run on the main ui thread as I intend.

My question:
Is this a bug in Microsoft’s code, or have I made a mistake somewhere?

Additional info:

  • I’m using .Net 4.0 (I haven’t yet tried this on .NET 4.5 RC)
  • I can reproduce this on both Debug/Release on any of x86/x64/Any CPU (on an x64 machine).
  • It reproduces consistently (I’d be interested if anyone can’t reproduce it).
  • I have legacy code that uses the BackgroundWorker–so I can’t easily change over to not using BackgroundWorker
  • I’ve confirmed that the code in MyContinueWith is running on the main ui thread.
  • I don’t know precisely why the StartLogicalOperation call helps cause the issue, that’s just what I narrowed it down to in my application.
  • 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-06-08T18:32:09+00:00Added an answer on June 8, 2026 at 6:32 pm

    The issue is fixed in .NET 4.5 RC (just tested it). So I assume it is a bug in .NET 4.0.
    Also, I’m guessing that these posts are referencing the same issue:

    • How can SynchronizationContext.Current of the main thread become null in a Windows Forms application?
    • http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/629d5524-c8db-466f-bc27-0ced11b441ba

    That’s unfortunate. Now I have to consider workarounds.

    Edit:
    From debugging into the .Net source, I have a little better understanding of when the issue would reproduce. Here’s some relevant code from ExecutionContext.cs:

            internal static void Run(ExecutionContext executionContext, ContextCallback callback,  Object state, bool ignoreSyncCtx) 
            {
                // ... Some code excluded here ...
    
                ExecutionContext ec = Thread.CurrentThread.GetExecutionContextNoCreate();
                if ( (ec == null || ec.IsDefaultFTContext(ignoreSyncCtx)) &&
    #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
                    SecurityContext.CurrentlyInDefaultFTSecurityContext(ec) && 
    #endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
                    executionContext.IsDefaultFTContext(ignoreSyncCtx)) 
                { 
                    callback(state);
                } 
                else
                {
                    if (executionContext == s_dummyDefaultEC)
                        executionContext = s_dummyDefaultEC.CreateCopy(); 
                    RunInternal(executionContext, callback, state);
                } 
            } 
    

    The issue only reproduces when we get into the “else” clause which calls RunInternal. This is because the RunInternal ends up replacing the the ExecutionContext which has the effect of changing what the current SynchronizationContext:

            // Get the current SynchronizationContext on the current thread 
            public static SynchronizationContext Current 
            {
                get
                { 
                    SynchronizationContext context = null;
                    ExecutionContext ec = Thread.CurrentThread.GetExecutionContextNoCreate(); 
                    if (ec != null) 
                    {
                        context = ec.SynchronizationContext; 
                    }
    
                    // ... Some code excluded ...
                    return context;
                }
            } 
    

    So, for my specific case, it was because the line `executionContext.IsDefaultFTContext(ignoreSyncCtx)) returned false. Here’s that code:

            internal bool IsDefaultFTContext(bool ignoreSyncCtx)
            { 
    #if FEATURE_CAS_POLICY 
                if (_hostExecutionContext != null)
                    return false; 
    #endif // FEATURE_CAS_POLICY
    #if FEATURE_SYNCHRONIZATIONCONTEXT
                if (!ignoreSyncCtx && _syncContext != null)
                    return false; 
    #endif // #if FEATURE_SYNCHRONIZATIONCONTEXT
    #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK 
                if (_securityContext != null && !_securityContext.IsDefaultFTSecurityContext()) 
                    return false;
    #endif //#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK 
                if (_logicalCallContext != null && _logicalCallContext.HasInfo)
                    return false;
                if (_illogicalCallContext != null && _illogicalCallContext.HasUserData)
                    return false; 
                return true;
            } 
    

    For me, that was returning false due to _logicalCallContext.HasInfo was true. Here’s that code:

    public bool HasInfo
    { 
        [System.Security.SecurityCritical]  // auto-generated
        get
        {
            bool fInfo = false; 
    
            // Set the flag to true if there is either remoting data, or 
            // security data or user data 
            if(
                (m_RemotingData != null &&  m_RemotingData.HasInfo) || 
                (m_SecurityData != null &&  m_SecurityData.HasInfo) ||
                (m_HostContext != null) ||
                HasUserData
              ) 
            {
                fInfo = true; 
            } 
    
            return fInfo; 
        }
    }
    

    For me, this was returning true because HasUserData was true. Here’s that code:

        internal bool HasUserData
        {
            get { return ((m_Datastore != null) && (m_Datastore.Count > 0));} 
        }
    

    For me, the m_DataStore would have items in it due to my call to Diagnostics.Trace.CorrelationManager.StartLogicalOperation("LogicalOperation");

    In summary, it looks like there are several different ways you could get the bug to reproduce. Hopefully, this example will serve to help others in determining if they are running into this same bug or not.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka

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.