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

标签 c#-4.0 .net-4.0 appdomain applicationdomain

请考虑以下代码:

// 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/

    相关文章:

    c# - 在c#中动态创建Json

    c# - 任务找不到 "AxImp.exe"

    c# - 类型 'X' 在类型 'Y.Z' 中不存在

    c# - 在 AppDomain 之间共享数据

    c# - 在自定义 AppDomain 中附加内存程序集

    使用 .NET 删除数据库后 MySql 查询变慢

    c# - 如何配置 IronPython.StdLib 2.7.3

    multithreading - 多线程WMI调用-如何最好地处理此问题?

    c# - Assembly.GetCustomAttributes 仍然被认为是最佳方法吗?

    c# - 当一个对象从 MarshalByRefObject 派生并且也被标记为 [Serializable] 时会发生什么?