Passing values back and forth appdomains

China☆狼群 提交于 2019-11-30 18:52:54

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.

For example:

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);
     }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!