简体   繁体   English

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

[英]Preventing Thread.CurrentPrincipal from propagating across application domains

Does anyone if it's possible to stop the current thread's IPrincipal from propagating over an application domain boundary? 有没有人可以阻止当前线程的IPrincipal在应用程序域边界上传播? I have no control over the IPrincipal that's assigned to the thread, but I do have control over creating the application domains. 我无法控制分配给该线程的IPrincipal,但我确实可以控制创建应用程序域。

(The reason I want to do this is to prevent a serialization error from occuring if the principal object type's assembly is unavailable in the other domain.) (我想这样做的原因是为了防止在主体对象类型的程序集在其他域中不可用时发生序列化错误。)

Edit: ExecutionContext.SuppressFlow looks promising, but it doesn't appear to achieve the goal. 编辑: ExecutionContext.SuppressFlow看起来很有希望,但它似乎没有实现目标。 The following prints "MyIdentity": 以下打印“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
}

You didn't run an asynchronous method, the target function is executed in the secondary appdomain by the same thread. 您没有运行异步方法,目标函数由同一个线程在辅助appdomain中执行。 So the principal doesn't change. 因此校长不会改变。 This works: 这有效:

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

Or if you just want to run the same thread with a specific context then you can use ExecutionContext.Run(): 或者,如果您只想运行具有特定上下文的相同线程,则可以使用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);

This appears to do what you want: 这似乎做你想要的:

System.Threading.ExecutionContext System.Threading.ExecutionContext

Specifically, take a look at the SuppressFlow method. 具体来说,看看SuppressFlow方法。

Chris 克里斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM