關(guān)于C#中動(dòng)態(tài)加載AppDomain的問(wèn)題
在操作系統(tǒng)中,利用進(jìn)程可以對(duì)正在運(yùn)行的應(yīng)用程序進(jìn)行隔離,每個(gè)應(yīng)用程序被加載到單獨(dú)的進(jìn)程中,并為其分配虛擬內(nèi)存,進(jìn)程無(wú)法直接訪問(wèn)物理內(nèi)存,只能通過(guò)操作系統(tǒng)將虛擬內(nèi)存映射到物理內(nèi)存中,并保證進(jìn)程之間的物理內(nèi)存不會(huì)重疊,但是進(jìn)程***的缺點(diǎn)就是效率問(wèn)題,尤其是進(jìn)程的切換開(kāi)銷很大,而進(jìn)程間不能共享內(nèi)存,所以不可能從一個(gè)進(jìn)程通過(guò)傳遞指針給另一個(gè)進(jìn)程。
在.NET中出現(xiàn)了一個(gè)新的概念:AppDomain——應(yīng)用程序域,所有.NET應(yīng)用程序都需要運(yùn)行在托管環(huán)境中,操作系統(tǒng)能提供的只有進(jìn)程,因此.NET程序需要通過(guò)AppDomain這個(gè)媒介來(lái)運(yùn)行在進(jìn)程中,同時(shí)使用該incheng提供的內(nèi)存空間,只要是.NET的應(yīng)用都會(huì)運(yùn)行在某個(gè)AppDomain中。
當(dāng)我們運(yùn)行一個(gè).NET應(yīng)用程序或者運(yùn)行庫(kù)宿主時(shí),OS會(huì)首先建立一個(gè)進(jìn)程,然后會(huì)在進(jìn)程中加載CLR(這個(gè)加載一般是通過(guò)調(diào)用_CorExeMain或者_(dá)CorBindToRuntimeEx方法來(lái)實(shí)現(xiàn)),在加載CLR時(shí)會(huì)創(chuàng)建一個(gè)默認(rèn)的AppDomain,它是CLR的運(yùn)行單元,程序的Main方法就是在這里執(zhí)行,這個(gè)默認(rèn)的AppDomain是唯一且不能被卸載的,當(dāng)該進(jìn)程消滅時(shí),默認(rèn)AppDomain才會(huì)隨之消失。
一個(gè)進(jìn)程中可以有多個(gè)AppDomain,且它們直接是相互隔離的,我們的Assembly是不能單獨(dú)執(zhí)行的,它必須被加載到某個(gè)AppDomain中,要想卸載一個(gè)Assembly就只能卸載其AppDomain。
最近在我所參加的一個(gè)項(xiàng)目中要實(shí)現(xiàn)這樣一個(gè)模塊:定制一個(gè)作業(yè)管理器,它可以定時(shí)的以不同頻率執(zhí)行某些.Net應(yīng)用程序或者存儲(chǔ)過(guò)程,這里的頻率可以是僅一次、每天、每周還是每月進(jìn)行執(zhí)行計(jì)劃的實(shí)施,對(duì)于調(diào)用存儲(chǔ)過(guò)程沒(méi)什么好說(shuō)的,但是調(diào)用.Net應(yīng)用程序的時(shí)候就需要考慮如下問(wèn)題:
一旦Assembly被作業(yè)管理器的服務(wù)器調(diào)用,(比如某個(gè)執(zhí)行計(jì)劃正好要被執(zhí)行了),在調(diào)用之前會(huì)將程序集加載到默認(rèn)AppDomain,然后執(zhí)行,這就有個(gè)問(wèn)題,如果我需要做替換或者刪除Assembly等這些操作的時(shí)候,由于Assembly已經(jīng)被默認(rèn)AppDomain加載,那么對(duì)它的更改肯定是不允許的,它會(huì)彈出這樣的錯(cuò)誤:
除非你關(guān)掉作業(yè)管理服務(wù)器,然后再操作,顯然這樣做是很不合理的。
并且默認(rèn)AppDomain是不能被卸載的,那么我們?cè)撛趺崔k呢,我想到的方法是動(dòng)態(tài)的加載Assembly,新建一個(gè)AppDomain,讓Assembly加載到這個(gè)新AppDomain中然后執(zhí)行,當(dāng)執(zhí)行完后卸載這個(gè)新的AppDomain即可,方法如下:
1、創(chuàng)建程序集加載類AssemblyDynamicLoader,該類用來(lái)創(chuàng)建新的AppDomain,并生成用來(lái)執(zhí)行.Net程序的RemoteLoader類:
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.IO;
- using System.Reflection;
- using System.Text;
- using Ark.Log;
- /// < summary>
- /// The local loader.
- /// < /summary>
- public class AssemblyDynamicLoader
- {
- /// < summary>
- /// The log util.
- /// < /summary>
- private static ILog log = LogManager.GetLogger(typeof(AssemblyDynamicLoader));
- /// < summary>
- /// The new appdomain.
- /// < /summary>
- private AppDomain appDomain;
- /// < summary>
- /// The remote loader.
- /// < /summary>
- private RemoteLoader remoteLoader;
- /// < summary>
- /// Initializes a new instance of the < see cref="LocalLoader"/> class.
- /// < /summary>
- public AssemblyDynamicLoader()
- {
- AppDomainSetup setup = new AppDomainSetup();
- setup.ApplicationName = "ApplicationLoader";
- setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
- setup.PrivateBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "private");
- setup.CachePath = setup.ApplicationBase;
- setup.ShadowCopyFiles = "true";
- setup.ShadowCopyDirectories = setup.ApplicationBase;
- this.appDomain = AppDomain.CreateDomain("ApplicationLoaderDomain", null, setup);
- String name = Assembly.GetExecutingAssembly().GetName().FullName;
- this.remoteLoader = (RemoteLoader)this.appDomain.CreateInstanceAndUnwrap(name, typeof(RemoteLoader).FullName);
- }
- /// < summary>
- /// Invokes the method.
- /// < /summary>
- /// < param name="fullName">The full name.< /param>
- /// < param name="className">Name of the class.< /param>
- /// < param name="argsInput">The args input.< /param>
- /// < param name="programName">Name of the program.< /param>
- /// < returns>The output of excuting.< /returns>
- public String InvokeMethod(String fullName, String className, String argsInput, String programName)
- {
- this.remoteLoader.InvokeMethod(fullName, className, argsInput, programName);
- return this.remoteLoader.Output;
- }
- /// < summary>
- /// Unloads this instance.
- /// < /summary>
- public void Unload()
- {
- try
- {
- AppDomain.Unload(this.appDomain);
- this.appDomain = null;
- }
- catch (CannotUnloadAppDomainException ex)
- {
- log.Error("To unload assembly error!", ex);
- }
- }
- }
2、創(chuàng)建RemoteLoader類,它可以在AppDomain中自由穿越,這就需要繼承System.MarshalByRefObject這個(gè)抽象類,這里RemoteLoader如果不繼承MarshalByRefObject類則一定會(huì)報(bào)錯(cuò)(在不同AppDomain間傳遞對(duì)象,該對(duì)象必須是可序列化的)。以RemoteLoader類做為代理來(lái)調(diào)用待執(zhí)行的.Net程序。
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.IO;
- using System.Reflection;
- using System.Text;
- /// < summary>
- /// The Remote loader.
- /// < /summary>
- public class RemoteLoader : MarshalByRefObject
- {
- /// < summary>
- /// The assembly we need.
- /// < /summary>
- private Assembly assembly = null;
- /// < summary>
- /// The output.
- /// < /summary>
- private String output = String.Empty;
- /// < summary>
- /// Gets the output.
- /// < /summary>
- /// < value>The output.< /value>
- public String Output
- {
- get
- {
- return this.output;
- }
- }
- /// < summary>
- /// Invokes the method.
- /// < /summary>
- /// < param name="fullName">The full name.< /param>
- /// < param name="className">Name of the class.< /param>
- /// < param name="argsInput">The args input.< /param>
- /// < param name="programName">Name of the program.< /param>
- public void InvokeMethod(String fullName, String className, String argsInput, String programName)
- {
- this.assembly = null;
- this.output = String.Empty;
- try
- {
- this.assembly = Assembly.LoadFrom(fullName);
- Type pgmType = null;
- if (this.assembly != null)
- {
- pgmType = this.assembly.GetType(className, true, true);
- }
- else
- {
- pgmType = Type.GetType(className, true, true);
- }
- Object[] args = RunJob.GetArgs(argsInput);
- BindingFlags defaultBinding = BindingFlags.DeclaredOnly | BindingFlags.Public
- | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase
- | BindingFlags.InvokeMethod | BindingFlags.Static;
- CultureInfo cultureInfo = new CultureInfo("es-ES", false);
- try
- {
- MethodInfo methisInfo = RunJob.GetItsMethodInfo(pgmType, defaultBinding, programName);
- if (methisInfo == null)
- {
- this.output = "EMethod does not exist!";
- }
- if (methisInfo.IsStatic)
- {
- if (methisInfo.GetParameters().Length == 0)
- {
- if (methisInfo.ReturnType == typeof(void))
- {
- pgmType.InvokeMember(programName, defaultBinding, null, null, null, cultureInfo);
- this.output = "STo call a method without return value successful.";
- }
- else
- {
- this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, null, null, cultureInfo);
- }
- }
- else
- {
- if (methisInfo.ReturnType == typeof(void))
- {
- pgmType.InvokeMember(programName, defaultBinding, null, null, args, cultureInfo);
- this.output = "STo call a method without return value successful.";
- }
- else
- {
- this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, null, args, cultureInfo);
- }
- }
- }
- else
- {
- if (methisInfo.GetParameters().Length == 0)
- {
- object pgmClass = Activator.CreateInstance(pgmType);
- if (methisInfo.ReturnType == typeof(void))
- {
- pgmType.InvokeMember(programName, defaultBinding, null, pgmClass, null, cultureInfo);
- this.output = "STo call a method without return value successful.";
- }
- else
- {
- 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'.
- }
- }
- else
- {
- object pgmClass = Activator.CreateInstance(pgmType);
- if (methisInfo.ReturnType == typeof(void))
- {
- pgmType.InvokeMember(programName, defaultBinding, null, pgmClass, args, cultureInfo);
- this.output = "STo call a method without return value successful.";
- }
- else
- {
- 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'.
- }
- }
- }
- }
- catch
- {
- this.output = (String)pgmType.InvokeMember(programName, defaultBinding, null, null, null, cultureInfo);
- }
- }
- catch (Exception e)
- {
- this.output = "E" + e.Message;
- }
- }
- }
其中的InvokeMethod方法只要提供Assembly的全名、類的全名、待執(zhí)行方法的輸入?yún)?shù)和其全名就可以執(zhí)行該方法,該方法可以是帶參數(shù)或不帶參數(shù),靜態(tài)的或者不是靜態(tài)的。
***這樣使用這兩個(gè)類:
- AssemblyDynamicLoader loader = new AssemblyDynamicLoader();
- String output = loader.InvokeMethod("fileName", "ymtcla", "yjoinp", "ymtpgm");
- loader.Unload();
【編輯推薦】