原文:
c# 动态加载和卸载DLL程序集
在 C++中加载和卸载DLL是一件很容易的事,LoadLibrary和FreeLibrary让你可以轻易的在程序中加载DLL,而后在任何地方卸载。在 C#中咱们也能使用Assembly.LoadFile实现动态加载DLL,可是当你试图卸载时,你会很惊讶的发现Assembly没有提供任何卸载的方 法。这是因为托管代码的自动垃圾回收机制会作这件事情,因此C#不提供释放资源的函数,一切由垃圾回收来作。
当AppDomain被卸载的时候,在该环境中的全部资源也将被回收。关于AppDomain的详细资料参考MSDN。下面是使用AppDomain实现动态卸载DLL的代码,
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string callingDomainName = AppDomain.CurrentDomain.FriendlyName;
AppDomain ad = AppDomain.CreateDomain("DLL Add test");
ProxyObject obj = (ProxyObject)ad.CreateInstanceFromAndUnwrap(@"WindowsFormsApplication1.exe", "WindowsFormsApplication1.ProxyObject");
obj.LoadAssembly();
String res = obj.Invoke("App.TestFrm", "Add", Convert.ToInt32 ( textBox1.Text) ,Convert.ToInt32 (textBox2 .Text) );
textBox3.Text = res;
AppDomain.Unload(ad);
obj = null;
}
}
class ProxyObject : MarshalByRefObject
{
Assembly assembly = null;
public void LoadAssembly()
{
assembly = Assembly.LoadFile(@"D:\Documents\Work\Dev\项目\应用程序域\应用程序域\WindowsFormsApplication1\bin\Debug\App.dll");
}
public String Invoke(string fullClassName, string methodName, params Object[] args)
{
if (assembly == null)
return "";
Type tp = assembly.GetType(fullClassName);
if (tp == null)
return "";
MethodInfo method = tp.GetMethod(methodName);
if (method == null)
return "";
Object obj = Activator.CreateInstance(tp);
String res = Convert.ToString ( method.Invoke(obj, args)) ;
return res ;
}
}
}
注意:
1. 要想让一个对象可以穿过AppDomain边界,必需要继承MarshalByRefObject类,不然没法被其余AppDomain使用。
2. 每一个线程都有一个默认的AppDomain,能够经过Thread.GetDomain()来获得