c#動態(tài)加載卸載DLL的方法
c#中通過反射可以方便的動態(tài)加載dll程序集,但是如果你需要對dll進行更新,卻發(fā)現(xiàn).net類庫沒有提供卸載dll程序集的方法。在.net 中,加入了應用程序域的概念,應用程序域是可以卸載的。也就是說,如果需要對動態(tài)加載的dll程序集進行更新,可以通過以下方法解決:
新建一個應用程序域,在該應用程序域中動態(tài)加載DLL,然后可以卸載掉該應用程序域。該應用程序域被卸載的時候,相關資源也會被回收。
要想這樣實現(xiàn),就要讓你程序的currentDomain和新建的newDomain之間進行通信,穿過應用程序域的邊界。從網(wǎng)上找到了某大牛的解決方法,抄下來留給自己看吧:
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()來得到
- C# WPF如何反射加載Geometry幾何圖形數(shù)據(jù)圖標
- c# WPF中自定義加載時實現(xiàn)帶動畫效果的Form和FormItem
- c# 實現(xiàn)網(wǎng)頁加載后將頁面截取為長圖片
- C# 根據(jù)表格偶數(shù)、奇數(shù)加載不同顏色
- C# 動態(tài)加載程序集信息
- C#中調用DLL時未能加載文件或程序集錯誤的處理方法(詳解)
- C#中加載dll并調用其函數(shù)的實現(xiàn)方法
- c# 動態(tài)加載dll文件,并實現(xiàn)調用其中的簡單方法
- C#使用Jquery zTree實現(xiàn)樹狀結構顯示 異步數(shù)據(jù)加載
- C#使用反射加載多個程序集的實現(xiàn)方法
- C#實現(xiàn)動態(tài)加載dll的方法
- 3種C# 加載Word的方法
相關文章
支持windows與linux的php計劃任務的實現(xiàn)方法
這篇文章主要介紹了支持windows與linux的php計劃任務的實現(xiàn)方法,較為詳細的講述了php計劃任務中涉及到的php程序實現(xiàn)方法、Windows計劃任務實現(xiàn)方法等,需要的朋友可以參考下2014-11-11
C#使用smtp發(fā)送帶附件的郵件實現(xiàn)方法
這篇文章主要介紹了C#使用smtp發(fā)送帶附件的郵件實現(xiàn)方法,可直接將string類型結果保存為附件,實例中備有相應的注釋便于理解,需要的朋友可以參考下2014-11-11

