关于C#中动态加载AppDomain的问题

在操作系统中,利用进程可以对正在运行的应用程序进行隔离,每个应用程序被加载到单独的进程中,并为其分配虚拟内存,进程无法直接访问物理内存,只能通过操作系统将虚拟内存映射到物理内存中,并保证进程之间的物理内存不会重叠,但是进程最大的缺点就是效率问题,尤其是进程的切换开销很大,而进程间不能共享内存,所以不可能从一个进程通过传递指针给另一个进程。

      在.NET中出现了一个新的概念:AppDomain——应用程序域,所有.NET应用程序都需要运行在托管环境中,操作系统能提供的只有进程,因此.NET程序需要通过AppDomain这个媒介来运行在进程中,同时使用该incheng提供的内存空间,只要是.NET的应用都会运行在某个AppDomain中。 

      当我们运行一个.NET应用程序或者运行库宿主时,OS会首先建立一个进程,然后会在进程中加载CLR(这个加载一般是通过调用_CorExeMain或者_CorBindToRuntimeEx方法来实现),在加载CLR时会创建一个默认的AppDomain,它是CLR的运行单元,程序的Main方法就是在这里执行,这个默认的AppDomain是唯一且不能被卸载的,当该进程消灭时,默认AppDomain才会随之消失。

      一个进程中可以有多个AppDomain,且它们直接是相互隔离的,我们的Assembly是不能单独执行的,它必须被加载到某个AppDomain中,要想卸载一个Assembly就只能卸载其AppDomain。

      最近在我所参加的一个项目中要实现这样一个模块:定制一个作业管理器,它可以定时的以不同频率执行某些.Net应用程序或者存储过程,这里的频率可以是仅一次、每天、每周还是每月进行执行计划的实施,对于调用存储过程没什么好说的,但是调用.Net应用程序的时候就需要考虑如下问题:

      一旦Assembly被作业管理器的服务器调用,(比如某个执行计划正好要被执行了),在调用之前会将程序集加载到默认AppDomain,然后执行,这就有个问题,如果我需要做替换或者删除Assembly等这些操作的时候,由于Assembly已经被默认AppDomain加载,那么对它的更改肯定是不允许的,它会弹出这样的错误: ,除非你关掉作业管理服务器,然后再操作,显然这样做是很不合理的。

      并且默认AppDomain是不能被卸载的,那么我们该怎么办呢,我想到的方法是动态的加载Assembly,新建一个AppDomain,让Assembly加载到这个新AppDomain中然后执行,当执行完后卸载这个新的AppDomain即可,方法如下:

1、创建程序集加载类AssemblyDynamicLoader,该类用来创建新的AppDomain,并生成用来执行.Net程序的RemoteLoader类:
  1. using System;

  2.     using System.Collections.Generic;
  3.     using System.Globalization;
  4.     using System.IO;
  5.     using System.Reflection;
  6.     using System.Text;
  7.     using Ark.Log;

  8.     /// <summary>
  9.     /// The local loader.
  10.     /// </summary>
  11.     public class AssemblyDynamicLoader
  12.     {
  13.         /// <summary>
  14.         /// The log util.
  15.         /// </summary>
  16.         private static ILog log = LogManager.GetLogger(typeof(AssemblyDynamicLoader));

  17.         /// <summary>
  18.         /// The new appdomain.
  19.         /// </summary>
  20.         private AppDomain appDomain;

  21.         /// <summary>
  22.         /// The remote loader.
  23.         /// </summary>
  24.         private RemoteLoader remoteLoader;

  25.         /// <summary>
  26.         /// Initializes a new instance of the <see cref="LocalLoader"/> class.
  27.         /// </summary>
  28.         public AssemblyDynamicLoader()
  29.         {
  30.             AppDomainSetup setup = new AppDomainSetup();
  31.             setup.ApplicationName = "ApplicationLoader";
  32.             setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
  33.             setup.PrivateBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "private");
  34.             setup.CachePath = setup.ApplicationBase;
  35.             setup.ShadowCopyFiles = "true";
  36.             setup.ShadowCopyDirectories = setup.ApplicationBase;

  37.             this.appDomain = AppDomain.CreateDomain("ApplicationLoaderDomain", null, setup);
  38.             String name = Assembly.GetExecutingAssembly().GetName().FullName;

  39.             this.remoteLoader = (RemoteLoader)this.appDomain.CreateInstanceAndUnwrap(name, typeof(RemoteLoader).FullName);
  40.         }

  41.         /// <summary>
  42.         /// Invokes the method.
  43.         /// </summary>
  44.         /// <param name="fullName">The full name.</param>
  45.         /// <param name="className">Name of the class.</param>
  46.         /// <param name="argsInput">The args input.</param>
  47.         /// <param name="programName">Name of the program.</param>
  48.         /// <returns>The output of excuting.</returns>
  49.         public String InvokeMethod(String fullName, String className, String argsInput, String programName)
  50.         {
  51.             this.remoteLoader.InvokeMethod(fullName, className, argsInput, programName);
  52.             return this.remoteLoader.Output;
  53.         }

  54.         /// <summary>
  55.         /// Unloads this instance.
  56.         /// </summary>
  57.         public void Unload()
  58.         {
  59.             try
  60.             {
  61.                 AppDomain.Unload(this.appDomain);
  62.                 this.appDomain = null;
  63.             }
  64.             catch (CannotUnloadAppDomainException ex)
  65.             {
  66.                 log.Error("To unload assembly error!", ex);
  67.             }
  68.         }
  69.     }
复制代码
2、创建RemoteLoader类,它可以在AppDomain中自由穿越,这就需要继承System.MarshalByRefObject这个抽象类,这里RemoteLoader如果不继承MarshalByRefObject类则一定会报错(在不同AppDomain间传递对象,该对象必须是可序列化的)。以RemoteLoader类做为代理来调用待执行的.Net程序。
  1. using System;
  2.     using System.Collections.Generic;
  3.     using System.Globalization;
  4.     using System.IO;
  5.     using System.Reflection;
  6.     using System.Text;

  7.     /// <summary>
  8.     /// The Remote loader.
  9.     /// </summary>
  10.     public class RemoteLoader : MarshalByRefObject
  11.     {
  12.         /// <summary>
  13.         /// The assembly we need.
  14.         /// </summary>
  15.         private Assembly assembly = null;

  16.         /// <summary>
  17.         /// The output.
  18.         /// </summary>
  19.         private String output = String.Empty;

  20.         /// <summary>
  21.         /// Gets the output.
  22.         /// </summary>
  23.         /// <value>The output.</value>
  24.         public String Output
  25.         {
  26.             get
  27.             {
  28.                 return this.output;
  29.             }
  30.         }

  31.         /// <summary>
  32.         /// Invokes the method.
  33.         /// </summary>
  34.         /// <param name="fullName">The full name.</param>
  35.         /// <param name="className">Name of the class.</param>
  36.         /// <param name="argsInput">The args input.</param>
  37.         /// <param name="programName">Name of the program.</param>
  38.         public void InvokeMethod(String fullName, String className, String argsInput, String programName)
  39.         {
  40.             this.assembly = null;
  41.             this.output = String.Empty;

  42.             try
  43.             {
  44.                 this.assembly = Assembly.LoadFrom(fullName);

  45.                 Type pgmType = null;
  46.                 if (this.assembly != null)
  47.                 {
  48.                     pgmType = this.assembly.GetType(className, true, true);
  49.                 }
  50.                 else
  51.                 {
  52.                     pgmType = Type.GetType(className, true, true);
  53.                 }

  54.                 Object[] args = RunJob.GetArgs(argsInput);

  55.                 BindingFlags defaultBinding = BindingFlags.DeclaredOnly | BindingFlags.Public
  56.                         | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase
  57.                         | BindingFlags.InvokeMethod | BindingFlags.Static;

  58.                 CultureInfo cultureInfo = new CultureInfo("es-ES", false);

  59.                 try
  60.                 {
  61.                     MethodInfo methisInfo = RunJob.GetItsMethodInfo(pgmType, defaultBinding, programName);
  62.                     if (methisInfo == null)
  63.                     {
  64.                         this.output = "EMethod does not exist!";
  65.                     }

  66.                     if (methisInfo.IsStatic)
  67.                     {
  68.                         if (methisInfo.GetParameters().Length == 0)
  69.                         {
  70.                             if (methisInfo.ReturnType == typeof(void))
  71.                             {
  72.                                 pgmType.InvokeMember(programName, defaultBinding, null, null, null, cultureInfo);
  73.                                 this.output = "STo call a method without return value successful.";
  74.                             }
  75.                             else
  76.                             {
  77.                                 this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, null, null, cultureInfo);
  78.                             }
  79.                         }
  80.                         else
  81.                         {
  82.                             if (methisInfo.ReturnType == typeof(void))
  83.                             {
  84.                                 pgmType.InvokeMember(programName, defaultBinding, null, null, args, cultureInfo);
  85.                                 this.output = "STo call a method without return value successful.";
  86.                             }
  87.                             else
  88.                             {
  89.                                 this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, null, args, cultureInfo);
  90.                             }
  91.                         }
  92.                     }
  93.                     else
  94.                     {
  95.                         if (methisInfo.GetParameters().Length == 0)
  96.                         {
  97.                             object pgmClass = Activator.CreateInstance(pgmType);

  98.                             if (methisInfo.ReturnType == typeof(void))
  99.                             {
  100.                                 pgmType.InvokeMember(programName, defaultBinding, null, pgmClass, null, cultureInfo);
  101.                                 this.output = "STo call a method without return value successful.";
  102.                             }
  103.                             else
  104.                             {
  105.                                 this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, pgmClass, null, cultureInfo);  //'ymtpgm' is program's name and the return value of it must be started with 'O'.
  106.                             }
  107.                         }
  108.                         else
  109.                         {
  110.                             object pgmClass = Activator.CreateInstance(pgmType);

  111.                             if (methisInfo.ReturnType == typeof(void))
  112.                             {
  113.                                 pgmType.InvokeMember(programName, defaultBinding, null, pgmClass, args, cultureInfo);
  114.                                 this.output = "STo call a method without return value successful.";
  115.                             }
  116.                             else
  117.                             {
  118.                                 this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, pgmClass, args, cultureInfo);  //'ymtpgm' is program's name and the return value of it must be started with 'O'.
  119.                             }
  120.                         }
  121.                     }
  122.                 }
  123.                 catch
  124.                 {
  125.                     this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, null, null, cultureInfo);
  126.                 }
  127.             }
  128.             catch (Exception e)
  129.             {
  130.                 this.output = "E" + e.Message;
  131.             }
  132.         }

  133.     }
复制代码
其中的InvokeMethod方法只要提供Assembly的全名、类的全名、待执行方法的输入参数和其全名就可以执行该方法,该方法可以是带参数或不带参数,静态的或者不是静态的。

      最后这样使用这两个类:
  1. AssemblyDynamicLoader loader = new AssemblyDynamicLoader();
  2. String output = loader.InvokeMethod("fileName", "ymtcla", "yjoinp", "ymtpgm");

  3. loader.Unload();
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值