Value | Expected Domains in Process | Each Domain Expected to Run ... | Code for MSCORLIB | Code for Assemblies in GAC | Code for Assemblies not in GAC |
---|---|---|---|---|---|
SingleDomain | One | N/A | Per-process | Per-domain | Per-domain |
MultiDomain | Many | Same Program | Per-process | Per-process | Per-process |
MultiDomainHost | Many | Different Programs | Per-process | Per-process | Per-domain |
在C++中加载和卸载DLL是一件很容易的事,LoadLibrary和FreeLibrary让你可以轻易的在程序中加载DLL,而后在任何地方 卸载。在C#中咱们也能使用Assembly.LoadFile实现动态加载DLL,可是当你试图卸载时,你会很惊讶的发现Assembly没有提供任何 卸载的方法。这是因为托管代码的自动垃圾回收机制会作这件事情,因此C#不提供释放资源的函数,一切由垃圾回收来作。
这引起了一个问题,用Assembly加载的DLL可能只在程序结束的时候才会被释放,这也意味着在程序运行期间没法更新被加载的DLL。而这个功能在某 些程序设计时是很是必要的,考虑你正在用反射机制写一个查看DLL中全部函数详细信息的程序,程序提供一个菜单让用户能够选择DLL文件,这时就须要让程 序可以卸载DLL,不然一旦用户从新获得新版本DLL时,必需要从新启动程序,从新选择加载DLL文件,这样的设计是用户没法忍受的。
C#也提供了实现动态卸载DLL的方法,经过AppDomain来实现。AppDomain是一个独立执行应用程序的环境,当AppDomain被卸载的 时候,在该环境中的全部资源也将被回收。关于AppDomain的详细资料参考MSDN。下面是使用AppDomain实现动态卸载DLL的代码,
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Reflection;
namespace UnloadDll
{
class Program
{
static void Main(string[] args)
{
string callingDomainName = AppDomain.CurrentDomain.FriendlyName;//Thread.GetDomain().FriendlyName;
Console.WriteLine(callingDomainName);
AppDomain ad = AppDomain.CreateDomain("DLL Unload test");
ProxyObject obj = (ProxyObject)ad.CreateInstanceFromAndUnwrap(@"UnloadDll.exe", "UnloadDll.ProxyObject");
obj.LoadAssembly();
obj.Invoke("TestDll.Class1", "Test", "It's a test");
AppDomain.Unload(ad);
obj = null;
Console.ReadLine();
}
}
class ProxyObject : MarshalByRefObject
{
Assembly assembly = null;
public void LoadAssembly()
{
assembly = Assembly.LoadFile(@"TestDLL.dll");
}
public bool Invoke(string fullClassName, string methodName, params Object[] args)
{
if(assembly == null)
return false;
Type tp = assembly.GetType(fullClassName);
if (tp == null)
return false;
MethodInfo method = tp.GetMethod(methodName);
if (method == null)
return false;
Object obj = Activator.CreateInstance(tp);
method.Invoke(obj, args);
return true;
}
}
}
注意:
1. 要想让一个对象可以穿过AppDomain边界,必需要继承MarshalByRefObject类,不然没法被其余AppDomain使用。
2. 每一个线程都有一个默认的AppDomain,能够经过Thread.GetDomain()来获得shell