SynchronizationContext.Current is null in Continuation on the main UI thread
Asked Answered
P

1

21

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.
Philipines answered 23/7, 2012 at 22:17 Comment(1)
Well, you got a diagnostic from that link. Are you also mixing WPF or WCF code into this Winforms app?Coral
P
21

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:

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.

Philipines answered 24/7, 2012 at 15:45 Comment(7)
You could contact Microsoft PSS to see if you can get a hotfix for it.Tillery
I submitted a bug report here: connect.microsoft.com/VisualStudio/feedback/details/755320/…Philipines
Your bug was closed as not reproducible :( and that is after one of the Microsoft reps said "We were able to reproduce this issue on .NetFramework 4.0 and confirmed that it had been fixed in our next release." I want to know if this is fixed in 4.0 or just 4.5.Latea
It is only fixed in 4.5. I had to work around it for 4.0. :(Philipines
Matt, did you find a workaround for this for 4.0? I have a portable class (Profile 158) that is necessarily 4.0 where I have this issue. Ahh, and I am doing this in an NUnit test which probably has the Diagnostics Trace call...Sassanid
@Sassanid I've posted the workaround I'm using here: #20953781Philipines
Thank you Matt. The struggle on my end is that I am using a portable class (profile 158) which does not support SetSynchronizationContext within it. I ended up saving the TaskScheduler the first time my class gets called and using that.Sassanid

© 2022 - 2024 — McMap. All rights reserved.