开发者

.NET AppDomain confusion

I haven't been able to find a very clear description of what's going on when using AppDomains, so hopefully someone will be able to enlighten me. I have a simple test program (basically ripped off the MSDN example):

using System;
using System.Reflection;

class Program
{
   public static void Main(string[] args)
   {            
      A localA = new A() { Name = "local" };
      localA.PrintAppDomain();

      AppDomain domain = AppDomain.CreateDomain("NewDomain");
      A remoteA = (A)domain.CreateInstanceAndUnwrap(
          Assembly.GetExecutingAssembly().FullName, "A");
      remoteA.Name = "remote";
      remoteA.PrintAppDomain();

      remoteA.PrintA(localA);
      remoteA.PrintAppDomain();
   }
}

[Serializable]
public class A : MarshalByRefObject
{
   public string Name { get; set; }

   public void 开发者_JS百科PrintAppDomain()
   {
      Console.WriteLine("In AppDomain {1}", 
          this.Name, AppDomain.CurrentDomain.FriendlyName);
   }

   public void PrintA(A a)
   {
      Console.WriteLine(a.ToString());
   }

   public override string ToString()
   {
      return String.Format("A : {0}", this.Name);
   }
}

When run, this prints out

In AppDomain test.exe

In AppDomain NewDomain

A : local

In AppDomain NewDomain

So... when I do remote.PrintA(localA), does this involve marshalling? Looking at the IL in Reflector suggests not, but I thought that data in one AppDomain couldn't access data from another AppDomain.

If I remove the : MarshalByRefObject from the declaration of A, the program prints

In AppDomain test.exe

In AppDomain test.exe

A : local

In AppDomain test.exe

What is happening in this case? Is a new AppDomain being created?


The behaviour you see is quite normal.

If you remove the MarshalByRefObject, since you have Serializable attribute, remoting will serialize the class for you and marshal the state to the main AppDomain. So when the method runs, in runs in the current AppDomain since it lives in the main AppDOmain (has been serialized and marshalled to current AppDomain).

If you keep MarshalByRefObject, remoting will make the call on the remote object.

If you remove both, it will throw up an exception since remoting objects need to have one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜