在.net中加载dll而不锁定它 [英] Load dll in .net without locking it

查看:166
本文介绍了在.net中加载dll而不锁定它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事一个任务,我必须加载dll并从类名等获取一些信息,但是当我将该DLL加载到我的代码中时,它被锁定,无法从源代码,直到我关闭加载程序,我已经尝试了一些解决方案,但没有一个适用于我


  1. Shadowcopy:在这种情况下当我影子复制装配,然后,如果我已经改变了某些东西在

    我的主要dll,它将仍然是旧的在我的加载应用程序。


  2. System.Reflection.assembly.loadfrom(System.IO.GetBytes( ASM-路径)); //工作有时但不总是


  3. System.Reflection.assembly.ReflectionOnlyConext(); //不工作


有没有适当的解决方案这个

解决方案

一种方法是读取一个文件的字节,并使用Assembly.Load的重载,它接收一个字节数组,类似于你在第二个例子中的工作。我不知道 System.IO.GetBytes 是否是 File.ReadAllBytes

  byte [] assemblyBytes = File.ReadAllBytes(asm-path); 
var assembly = Assembly.Load(assemblyBytes);

但是,由于您无法卸载程序集,因此您可能无法做到这一点在它被加载之后。要解决这个问题,如果需要,您可以将程序集加载到自己的 AppDomain ,然后卸载AppDomain。

  AppDomain ad = new AppDomain.CreateDomain( NewAssemblyAD); 
byte [] assemblyBytes = File.ReadAllBytes(asm-path);
var assembly = ad.Load(assemblyBytes);

完成程序集对象,你可以卸载AppDomain。

  AppDomain.Unload(ad); 


I Am working on a task in which i have to load dll and get some information from it like class names and etc... but when i load that dll into my code, it gets locked and can't be build from source code until i close loading program, I have tried certain solution but none of them works for me

  1. Shadowcopy: in this case when i shadow copy assembly then after that if i have changed something in
    my main dll it will be still old one in my loading application.

  2. System.Reflection.assembly.loadfrom(System.IO.GetBytes("asm-path")); //work sometimes but not always

  3. System.Reflection.assembly.ReflectionOnlyConext(); //Does not work

Is there any proper solution to this

解决方案

One way would be to read the bytes of a file and use the overload of Assembly.Load that takes in a byte array similar to what you're doing in your second example. I'm not sure what System.IO.GetBytes is but try File.ReadAllBytes instead.

byte[] assemblyBytes = File.ReadAllBytes("asm-path");
var assembly = Assembly.Load(assemblyBytes);

However this may not be enough depending on what you want to do since you can't unload an assembly after it's been loaded. To workaround this, if you need to, you could load the assembly into its own AppDomain and then unload the AppDomain once you've finished with it.

AppDomain ad = new AppDomain.CreateDomain("NewAssemblyAD");
byte[] assemblyBytes = File.ReadAllBytes("asm-path");
var assembly = ad.Load(assemblyBytes);  

Once you've finished with the assembly object, you can unload the AppDomain.

AppDomain.Unload(ad);

这篇关于在.net中加载dll而不锁定它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆