C#中动态加载和卸载DLL

来源:互联网 发布:算法 英语 编辑:程序博客网 时间:2024/04/29 07:11

C++中加载和卸载DLL是一件很容易的事,LoadLibraryFreeLibrary让你能够轻易的在程序中加载DLL,然后在任何地方卸载。在C#中我们也能使用Assembly.LoadFile实现动态加载DLL,但是当你试图卸载时,你会很惊讶的发现Assembly没有提供任何卸载的方法。这是由于托管代码的自动垃圾回收机制会做这件事情,所以C#不提供释放资源的函数,一切由垃圾回收来做。

AppDomain被卸载的时候,在该环境中的所有资源也将被回收。关于AppDomain的详细资料参考MSDN。下面是使用AppDomain实现动态卸载DLL的代码:

using System;

 

namespace UnloadDll

{

        public class Program

        {

                static void Main(string[] args)

                {

                        string callingDomainName = AppDomain.CurrentDomain.FriendlyName;

                        Console.WriteLine(callingDomainName);

                        AppDomain ad = AppDomain.CreateDomain("DLL Unload test");

                        ProxyObject obj = (ProxyObject)ad.CreateInstanceFromAndUnwrap(@"UnloadDll.exe", "UnloadDll.ProxyObject");

                        obj.LoadAssembly();

                        obj.Invoke("UnloadDll.TestClass", "Test", "It's a test");

                        AppDomain.Unload(ad);

                        obj = null;

                        Console.ReadLine();

                }

        }

}

using System;

using System.IO;

using System.Reflection;

 

namespace UnloadDll

{

        public class ProxyObject : MarshalByRefObject

        {

                Assembly assembly = null;

               

                public void LoadAssembly()

                {

                        string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"UnloadDll.exe");

                        assembly = Assembly.LoadFile(path);

                }

 

                public bool Invoke(string fullClassName, string methodName, params Object[] args)

                {

                        if(assembly == null)

                                return false;

 

                        Type t = assembly.GetType(fullClassName);

                        if (t == null)

                                return false;

 

                        MethodInfo method = t.GetMethod(methodName);

                        if (method == null)

                                return false;

 

                        Object obj = Activator.CreateInstance(t);

                        method.Invoke(obj, args);

                        return true;

                }

        }

}

using System;

 

namespace UnloadDll

{

        public class TestClass

        {

                public void Test(string info)

                {

                        Console.WriteLine(info);

                }

        }

}

原创粉丝点击