C#.Net 如何動態加載與卸載程序集(.dll或者.exe)1----C#中動態加載和卸載DLL


我們知道在C++中加載和卸載DLL是一件很容易的事,LoadLibrary和FreeLibrary讓你能夠輕易的在程序中加載DLL,然后在任何地方卸載。

在C#中我們也能使用Assembly.LoadFile實現動態加載DLL,但是當你試圖卸載時,你會很驚訝的發現Assembly沒有提供任何卸載的方法。這是由於托管代碼的自動垃圾回收機

制會做這件事情,所以C#不提供釋放資源的函數,一切由垃圾回收來做。

但是我們可以通過應用程序域(AppDomain)來實現加載域卸載,如下會演示如何使用的。當AppDomain被卸載的時候,在該環境中的所有資源也將被回收。

關於AppDomain的更多詳細資料可以參考參考MSDN。

下面是使用AppDomain實現動態卸載DLL的代碼
 
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()來得到


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM