gpt4 book ai didi

c#-4.0 - 非静态委托(delegate)的 DoCallBack CrossAppDomainDelegate 行为

转载 作者:行者123 更新时间:2023-12-04 14:46:37 24 4
gpt4 key购买 nike

请考虑以下代码:

// Create a new application domain
AppDomain ad = AppDomain.CreateDomain("New domain");

Worker work = new Worker();

// if Worker class is marked as 'MarshalByRefObject', this will run in current
// appdomain.
// if Worker class is NOT marked as 'MarshalByRefObject' and is marked as
// 'Serializable', this will run in a new appdomain.
ad.DoCallBack(work.PrintDomain);
// or ad.DoCallBack(new CrossAppDomainDelegate(work.PrintDomain));

// But for static methods:
// If ppp method is static, no marking is required and it will run in
// a new AppDomain.
ad.DoCallBack(Worker.ppp);

我们如何解释 DoCallBack 的这种行为? ?
  • 为什么是非静态方法PrintDomain Worker 时在当前域中执行类(class)标记为 MarshalByRefObject ?
  • 为什么是非静态方法PrintDomain Worker 时在新的 AppDomain 中执行类(class)标记为 Serializable ?
  • 为什么静态方法不需要任何标记?
  • 最佳答案

    Why is the non-static method PrintDomain executed in the current domain when the Worker class is marked MarshalByRefObject?



    因为这就是 MBRO 所做的,所以它会为您在主 appdomain 中创建的对象创建一个代理。它将来自辅助 appdomain 的调用编码到拥有对象的 appdomain,即主 appdomain。

    Why is the non-static method PrintDomain executed in a new AppDomain when the Worker class is marked Serializable?



    因为那个场景不使用代理。对象本身从主要应用程序域编码到辅助应用程序域。可能是因为您将其标记为 [Serializable]。因此,该调用在辅助 appdomain 中执行。

    Why doesn't the static method need any markings?



    目前尚不清楚“标记”是什么意思,但对于静态方法来说并没有什么不同。一些代码可以玩,删除基类上的注释来比较两个场景:
    using System;

    class Program {
    static void Main(string[] args) {
    var dom = AppDomain.CreateDomain("Test");
    var obj = new WorkerMbro();
    dom.DoCallBack(obj.PrintDomain);
    dom.DoCallBack(obj.PrintDomainStatic);
    Console.ReadLine();
    }
    }
    [Serializable]
    class WorkerMbro /* : MarshalByRefObject */ {
    public void PrintDomain() {
    Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
    }
    public void PrintDomainStatic() {
    Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
    }
    }

    发布的输出:
    Test
    Test

    删除了注释的输出,因此使用了代理:
    ConsoleApplication1.vshost.exe
    ConsoleApplication1.vshost.exe

    关于c#-4.0 - 非静态委托(delegate)的 DoCallBack CrossAppDomainDelegate 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16583169/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com