传递值来回的AppDomain来回、AppDomain

由网友(安度°)分享简介:我有以下的code:public class AppDomainArgs : MarshalByRefObject {public string myString;}static AppDomainArgs ada = new AppDomainArgs() { myString = "abc" };static vo...

我有以下的code:

    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!";
    }

我觉得做这会使我的ada.myString有工作!在主应用程序域,但它没有。我认为,通过自MarshalByRefObject inhering取得2日AppDomain的任何更改也将反映在原来的(我认为这将只是一个在主应用程序域代理实物!)?

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!)?

感谢

推荐答案

在你的code的问题是,你从来没有真正越过边界的对象;因此你可以使用两个 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);
     }
}
阅读全文

相关推荐

最新文章