卸载使用 Assembly.LoadFrom() 加载的程序集

Unloading the Assembly loaded with Assembly.LoadFrom()(卸载使用 Assembly.LoadFrom() 加载的程序集)
本文介绍了卸载使用 Assembly.LoadFrom() 加载的程序集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查加载 dll 后运行 GetTypes() 的时间量.代码如下.

I need to check the time amount to run GetTypes() after loading the dll. The code is as follows.

Assembly assem = Assembly.LoadFrom(file);
sw = Stopwatch.StartNew();
var types1 = assem.GetTypes();
sw.Stop();
double time1 = sw.Elapsed.TotalMilliseconds;

我想卸载并重新加载 dll 以检查再次运行 GetTypes() 所花费的时间.

I'd like to unload and reload the dll to check the time to spend in running GetTypes() again.

  • 如何卸载?assem = null 够好吗?
  • 有没有明确的方法来调用垃圾收集器来回收分配给 assem 的资源?

推荐答案

不幸的是,一旦程序集被加载,您就无法卸载它.但是您可以卸载 AppDomain.您可以做的是创建一个新的 AppDomain (AppDomain.CreateDomain(...) ),将程序集加载到此 appdomain 中以使用它,然后在需要时卸载 AppDomain.卸载 AppDomain 时,将卸载所有已加载的程序集.(请参阅参考)

Unfortunately you can not unload an assembly once it is loaded. But you can unload an AppDomain. What you can do is to create a new AppDomain (AppDomain.CreateDomain(...) ), load the assembly into this appdomain to work with it, and then unload the AppDomain when needed. When unloading the AppDomain, all assemblies that have been loaded will be unloaded. (See reference)

要调用垃圾收集器,可以使用

To call the garbage collector, you can use

GC.Collect(); // collects all unused memory
GC.WaitForPendingFinalizers(); // wait until GC has finished its work
GC.Collect();

GC 在后台线程中调用终结器,这就是为什么您必须等待并再次调用 Collect() 以确保您删除了所有内容.

GC calls the finalizers in a background thread, that's why you have to wait and call Collect() again to make sure you deleted everything.

这篇关于卸载使用 Assembly.LoadFrom() 加载的程序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)