几段代码演示多个AppDomain工作的特性
时间:2011-05-26 来源:_Mgen
下面代码需要读者对.NET AppDomain和Remoting有一定了解。
1. 每一个AppDomain都保留自己加载程序集的静态字段成员
using System; using System.Text; using System.Collections.Generic; using System.Reflection;
namespace Mgen.TTC { class Program { static int num = -3; static void Main() { Console.WriteLine("设置num为{0}", num = 17); var newDomain = AppDomain.CreateDomain("另一个AppDomain");
GetNumber(); newDomain.DoCallBack(GetNumber); Console.WriteLine();
PrintLoadedAss(AppDomain.CurrentDomain); PrintLoadedAss(newDomain); }
static void GetNumber() { string name = AppDomain.CurrentDomain.FriendlyName; if (String.Equals(name, Assembly.GetExecutingAssembly().GetName().Name + ".exe")) name = "默认AppDomain"; Console.WriteLine("num在{0}中的值是:{1}", name, num); }
static void PrintLoadedAss(AppDomain dom) { Console.WriteLine("{0}加载的程序集:", dom.FriendlyName); foreach (var ass in dom.GetAssemblies()) Console.WriteLine(ass.FullName); Console.WriteLine(); } } }
|
运行结果:
设置num为17 num在默认AppDomain中的值是:17 num在另一个AppDomain中的值是:-3
TTC.exe加载的程序集: mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 TTC, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
另一个AppDomain加载的程序集: mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 TTC, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
|
2. Marshal By Value(MBV)和Marshal By Reference(MBR)
using System; using System.Text; using System.Collections.Generic; using System.Reflection; using System.Runtime.Remoting;
namespace Mgen.TTC { [Serializable] class MBV { }
class MBR : MarshalByRefObject { }
class Program { static void Main() { test("Mgen.TTC.MBV"); test("Mgen.TTC.MBR"); } static void test(string type) { var newdom = AppDomain.CreateDomain("另一个AppDomain"); ObjectHandle objhdl = newdom.CreateInstance(Assembly.GetExecutingAssembly().FullName, type); var obj = objhdl.Unwrap();
Console.WriteLine("类型: {0}", type); Console.WriteLine("不在当前执行AppDomain?: " + RemotingServices.IsObjectOutOfAppDomain(obj)); Console.WriteLine("不在当前执行Context?: " + RemotingServices.IsObjectOutOfContext(obj)); Console.WriteLine("是否是透明代理?: " + RemotingServices.IsTransparentProxy(obj)); Console.WriteLine();
AppDomain.Unload(newdom); } } }
|
运行结果:
类型: Mgen.TTC.MBV 不在当前执行AppDomain?: False 不在当前执行Context?: False 是否是透明代理?: False
类型: Mgen.TTC.MBR 不在当前执行AppDomain?: True 不在当前执行Context?: True 是否是透明代理?: True
|
版权
作者:Mgen(刘圆圆),转载请注明此出处。