private static void ThreadsTest() { var myIdentity = new MyIdentity(true, "kamil", "manual"); var myPrincipal = new GenericPrincipal(myIdentity, new[] { "code author" }); // Thread.CurrentThread.GetExecutionContextReader().LogicalCallContext.Principal = myPrincipal Thread.CurrentPrincipal = myPrincipal; System.Runtime.Remoting.Messaging.CallContext.LogicalSetData("name", "from main thread 2"); // Thread.CurrentPrincipal sets Principal for the current thread and then it`s copied to child treads // the same is true for the context ShowCurrentThreadContext(); // "ContextID: 0"; kamil var newThread = new Thread(() => { ShowCurrentThreadContext(); Console.WriteLine(CallContext.LogicalGetData("name")); var myIdentity2 = new MyIdentity(true, "kamil2", "manual"); var myPrincipal2 = new GenericPrincipal(myIdentity2, new[] { "code author" }); Thread.CurrentPrincipal = myPrincipal2; ShowCurrentThreadContext(); }); newThread.Start(); newThread.Join(); ShowCurrentThreadContext(); }
private static void TaskTest() { var myIdentity = new MyIdentity(true, "kamil", "manual"); var myPrincipal = new GenericPrincipal(myIdentity, new[] { "code author" }); // Thread.CurrentThread.GetExecutionContextReader().LogicalCallContext.Principal = myPrincipal Thread.CurrentPrincipal = myPrincipal; CallContext.LogicalSetData("name", "from main thread"); // Thread.CurrentPrincipal устанавливает Principal для текущего потока и далее он копируется в дочерние потоки (то же верно для контекста) ShowCurrentThreadContext(); // "ContextID: 0"; kamil var t = Task.Run(() => { Console.WriteLine(CallContext.LogicalGetData("name")); ShowCurrentThreadContext(); var myIdentity2 = new MyIdentity(true, "kamil2", "manual"); var myPrincipal2 = new GenericPrincipal(myIdentity2, new[] { "code author" }); Thread.CurrentPrincipal = myPrincipal2; ShowCurrentThreadContext(); }); t.Wait(); ShowCurrentThreadContext(); }