在应用程序域之间来回传递值 [英] Passing values back and forth appdomains

查看:29
本文介绍了在应用程序域之间来回传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

    public class AppDomainArgs : MarshalByRefObject {
        public string myString;
    }

    static AppDomainArgs ada = new AppDomainArgs() { myString = "abc" };

    static void Main(string[] args) {
        AppDomain domain = AppDomain.CreateDomain("Domain666");
        domain.DoCallBack(MyNewAppDomainMethod);
        Console.WriteLine(ada.myString);
        Console.ReadKey();
        AppDomain.Unload(domain);
    }

    static void MyNewAppDomainMethod() {
        ada.myString = "working!";
    }

我认为 make 这会让我的 ada.myString 有工作!"在主应用程序域上,但它没有.我认为通过从 MarshalByRefObject 继承,在第二个应用程序域上所做的任何更改也会反映在原始应用程序域中(我认为这只是主应用程序域上真实对象的代理!)?

I thought make this would make my ada.myString have "working!" on the main appdomain, but it doesn't. I thought that by inhering from MarshalByRefObject any changes made on the 2nd appdomain would reflect also in the original one(I thought this would be just a proxy to the real object on the main appdomain!)?

谢谢

推荐答案

您代码中的问题是您实际上从未将对象传递过边界;因此,您有两个 ada 实例,每个应用程序域中一个(静态字段初始值设定项在两个应用程序域上运行).您需要将实例传递到边界上,以便 MarshalByRefObject 魔法启动.

The problem in your code is that you never actually pass the object over the boundary; thus you have two ada instances, one in each app-domain (the static field initializer runs on both app-domains). You will need to pass the instance over the boundary for the MarshalByRefObject magic to kick in.

例如:

using System;
class MyBoundaryObject : MarshalByRefObject {
    public void SomeMethod(AppDomainArgs ada) {
        Console.WriteLine(AppDomain.CurrentDomain.FriendlyName + "; executing");
        ada.myString = "working!";
    }
}
public class AppDomainArgs : MarshalByRefObject {
    public string myString { get; set; }
}
static class Program {
     static void Main() {
         AppDomain domain = AppDomain.CreateDomain("Domain666");
         MyBoundaryObject boundary = (MyBoundaryObject)
              domain.CreateInstanceAndUnwrap(
                 typeof(MyBoundaryObject).Assembly.FullName,
                 typeof(MyBoundaryObject).FullName);

         AppDomainArgs ada = new AppDomainArgs();
         ada.myString = "abc";
         Console.WriteLine("Before: " + ada.myString);
         boundary.SomeMethod(ada);
         Console.WriteLine("After: " + ada.myString);         
         Console.ReadKey();
         AppDomain.Unload(domain);
     }
}

这篇关于在应用程序域之间来回传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆