6

Please consider the following piece of code:

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

How do we explain this behavior of DoCallBack?

  1. Why is the non-static method PrintDomain executed in the current domain when the Worker class is marked MarshalByRefObject?
  2. Why is the non-static method PrintDomain executed in a new AppDomain when the Worker class is marked Serializable?
  3. Why doesn't the static method need any markings?
4

1 回答 1

7

为什么Worker类被标记为MarshalByRefObject时,非静态方法PrintDomain在当前域中执行?

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

为什么当Worker类被标记为Serializable时,非静态方法PrintDomain在新的AppDomain中执行?

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

为什么静态方法不需要任何标记?

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

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
于 2013-05-23T21:08:04.687 回答