防止Thread.CurrentPrincipal跨应用程序域传播

有没有人可以阻止当前线程的IPrincipal在应用程序域边界上传播? 我无法控制分配给该线程的IPrincipal,但我确实可以控制创建应用程序域。

(我想这样做的原因是为了防止在主体对象类型的程序集在另一个域中不可用时发生序列化错误。)

编辑: ExecutionContext.SuppressFlow看起来很有希望,但它似乎没有实现目标。 以下打印“MyIdentity”:

 static void Main () { ExecutionContext.SuppressFlow (); Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("MyIdentity"), "Role".Split ()); AppDomain.CreateDomain ("New domain").DoCallBack (Isolated); } static void Isolated () { Console.WriteLine ("Current principal: " + Thread.CurrentPrincipal.Identity.Name); // MyIdentity } 

您没有运行异步方法,目标函数由同一个线程在辅助appdomain中执行。 因此校长不会改变。 这有效:

  var flow = ExecutionContext.SuppressFlow(); Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("MyIdentity"), "Role".Split()); ThreadPool.QueueUserWorkItem((x) => { AppDomain.CreateDomain("New domain").DoCallBack(Isolated); }); flow.Undo(); 

或者,如果您只想运行具有特定上下文的相同线程,则可以使用ExecutionContext.Run():

  var copy = ExecutionContext.Capture(); Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("MyIdentity"), "Role".Split()); ExecutionContext.Run(copy, new ContextCallback((x) => { AppDomain.CreateDomain("New domain").DoCallBack(Isolated); }), null); 

这似乎做你想要的:

System.Threading.ExecutionContext

具体来说,看看SuppressFlow方法。

克里斯