加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c#-4.0 – 非静态委托的DoCallBack CrossAppDomainDelegate行为

发布时间:2020-12-15 08:42:27 所属栏目:百科 来源:网络整理
导读:请考虑以下代码: // Create a new application domainAppDomain 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
请考虑以下代码:
// 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的这种行为?

>当Worker类标记为MarshalByRefObject时,为什么在当前域中执行非静态方法PrintDomain?
>当Worker类标记为Serializable时,为什么在新的AppDomain中执行非静态方法PrintDomain?
>为什么静态方法不需要任何标记?

解决方法

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

因为这是MBRO所做的,它会为您在主应用程序域中创建的对象创建代理.其中将来自辅助应用程序域的调用编组到拥有该对象(主应用程序域)的应用程序域.

Why is the non-static method PrintDomain executed in a new AppDomain when the Worker class is marked 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读