.NET 中动态加载DLL ,调用完之后及时释放。

问题:

很多时候希望通过反射动态的加载一个程序集,通过反射调用其方法,调用完之后希望能够及时释放加载的DLL 文件,以便释放资源和更新dll

解决:

目前对于 Assembly, CLR 没有提供卸载 Assembly 的方法。而 Assembly 是 驻留在 Appdomain 中,Appdomain 是可以动态卸载和创建的。


比如有一个动态生成的类库:

None.gif public   class  HelloWorld : MarshalByRefObject
None.gif
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public HelloWorld()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    
public void Task1(string s)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif    Console.WriteLine(
"Task1 " + s);
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}


动态的调用
None.gif //  File: Invoke.cs
None.gif

None.gif
using  System;
None.gif
using  System.Reflection;
None.gif
using  System.Runtime.Remoting;
None.gif
None.gif
None.gif
None.gif
public   class  InvokeMethod
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif
InBlock.gif
public static void Main( String[] argv )
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif
dot.gif{
InBlock.gif
InBlock.gifAppDomainSetup info 
= new AppDomainSetup();
InBlock.gifinfo.ApplicationBase 
= "file:///" + System.Environment.CurrentDirectory;
InBlock.gifAppDomain dom 
= AppDomain.CreateDomain("RemoteDomain"null, info);
InBlock.gifAssembly asm 
=Assembly.Load("HelloWorld2");
InBlock.gifObject obj
=asm.CreateInstance("HelloWorld");
InBlock.gifMethodInfo minfo
=asm.GetType("HelloWorld").GetMethod("Task1") ;
ExpandedSubBlockStart.gifContractedSubBlock.gifminfo.Invoke(obj,
new string []dot.gif{"Task 1"});
InBlock.gifAppDomain.Unload(dom);
InBlock.gif
ExpandedSubBlockEnd.gif}

InBlock.gif
ExpandedBlockEnd.gif}

None.gif



限制:
动态加载的dll 必须和host 在同一目录

参考:

http://www.gotdotnet.com/team/clr/AppdomainFAQ.aspx#_Toc514058481

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值