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?