如何从主AppDomain卸载程序集?

时间:2020-03-06 14:37:22  来源:igfitidea点击:

我想知道如何卸载加载到主AppDomain中的程序集。

我有以下代码:

var assembly = Assembly.LoadFrom( FilePathHere );

完成后,我需要/希望能够卸载此程序集。

谢谢你的帮助。

解决方案

我们无法从appdomain卸载程序集。我们可以销毁appdomain,但是一旦将程序集加载到appdomain中,它将在appdomain的整个生命周期内都存在。

请参阅Jason Zander对"为什么没有Assembly.Unload方法?"的解释。

如果我们使用的是3.5,则可以使用AddIn Framework使其更易于管理/调用不同的AppDomain(可以卸载,卸载所有程序集)。如果我们使用的是之前的版本,则需要自己创建一个新的应用程序域以将其卸载。

我们必须先卸载整个AppDomain,才能卸载程序集。原因如下:

You are running that code in the app domain. That means there are potentially call sites and call stacks with addresses in them that are expecting to keep working. 
  Say you did manage to track all handles and references to already running code by an assembly.  Assuming you didn't ngen the code, once you successfully freed up the assembly, you have only freed up the metadata and IL.  The JIT'd code is still allocated in the app domain loader heap (JIT'd methods are allocated sequentially in a buffer in the order in which they are called). 
  The final issue relates to code which has been loaded shared, otherwise more formally know as "domain neutral" (check out /shared on the ngen tool).  In this mode, the code for an assembly is generated to be executed from any app domain (nothing hard wired).  
  
  
  It is recommended that you design your application around the application domain boundary naturally, where unload is fully supported.

如果我们想要临时代码,然后可以将其卸载,则根据需要,DynamicMethod类可能会做我们想要的事情。但是,这不会给我们上课。

我们应该将临时程序集加载到另一个AppDomain中,当不使用时,我们可以卸载该AppDomain。安全又快速。

这是一个很好的示例,说明如何在运行时编译并运行dll,然后卸载所有资源:
http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm