c# 动态加载和卸载DLL程序集

原文: 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()来得到

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/11822771.html
今日推荐