Thread.CurrentPrincipal corrupts current SynchronizationContext

Answered Thread.CurrentPrincipal corrupts current SynchronizationContext

  • Wednesday, December 07, 2011 6:30 PM
     
     

    When Thread.CurrentPrincipal is executed on a thread with synchronization context then tasks scheduled on the corresponding synchronization   context don’t have the current synchronization context set any longer. For this code:

     

     

     var sch = TaskScheduler.FromCurrentSynchronizationContext();

                System.Threading.Tasks.Task.Factory.StartNew(

                    () => Console.Out.WriteLine("SynchronizationContext.Current: " + SynchronizationContext.Current),

                    CancellationToken.None, TaskCreationOptions.None, sch);

     

                Console.Out.WriteLine("Thread.CurrentPrincipal: " + Thread.CurrentPrincipal);

     

                System.Threading.Tasks.Task.Factory.StartNew(

                    () => Console.Out.WriteLine("SynchronizationContext.Current: " + SynchronizationContext.Current),

                    CancellationToken.None, TaskCreationOptions.None, sch);

     

     

    The output is:

    Thread.CurrentPrincipal: System.Security.Principal.GenericPrincipal

    SynchronizationContext.Current: System.Windows.Threading.DispatcherSynchronizationContext

    SynchronizationContext.Current:

     

    The second task doesn’t have current context any longer even though it executes on the same thread. It looks like TPL/.net bug. Does anybody kno about any workaround?

     

     

     


All Replies

  • Thursday, December 08, 2011 11:23 PM
     
     Answered

    This is a known issue in .NET 4.  If you have a chance to try the .net 4.5 developer preview, the bug should be fixed there.  The workaround would be to get SynchronizationContext.Current before starting the task, and then call SynchronizationContext.SetSynchronizationContext inside of the task body.