什么情况下需要调用GC.Collect两次

Under what circumstances, we need to call GC.Collect twice(什么情况下需要调用GC.Collect两次)

本文介绍了什么情况下需要调用GC.Collect两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个 WPF 应用程序,它基于 Unity 和 MMVVVM 模式.在应用程序生命周期中可以有多个项目生命周期,在每个项目生命周期之后我们都会进行手动 Tear Down 并尝试释放 ViewModels 的所有引用.对于 Unity 的事件订阅,我们使用弱引用.所以我们假设在tear down之后,我们可能会调用GC Collect,这样所有的垃圾对象都被垃圾回收了.我们还有另一种手动取消订阅所有事件的选项,但我们更喜欢垃圾收集,因为它会为我们清除大约 200MB 的空间,这将有助于新项目的加载.

We have a WPF application, based on Unity with MMVVVM pattern. In application life cycle there can be several project life cycles, after each project life cycle we do a manual Tear Down and try to free all the reference of ViewModels. For event subscriptions with Unity we are using Weak references. So we are assuming that after tear down, we may call GC Collect, so that all the garbage objects are garbage collected. We have another option of manually un-subscribing all the events, but we are preferring garbage collection because it will clear around 200MB for us, which will facilitate new project loading.

对于一个实例,我们观察到,如果我只调用 GC.Collect 一次,它的引用仍会在内存中保留一段时间.

With one instance, we are observing that, If i call GC.Collect only one time, its reference still remains in memory for sometime.

GC.Collect();
GC.WaitForPendingFinalizers(); 

但如果我尝试连续两次调用 GC,它会很好地清理所有内容.

But if i try Calling GC twice in a row, its cleans up everything nicely.

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();

任何想法或建议都将受到高度赞赏.

Any thoughts or pointers will be highly appreciated.

更新:

类中没有定义终结器.

现在我也在考虑一个案例,其中这个对象被另一个可能有终结器的对象引用.在我们的框架中,我们只有 DBProvider 的终结器,所以我不认为,即使是这种情况.

Now i am also considering a case, in which this object is referred in another object which might have a finalizer. In Our framework, we have finalizer only for DBProvider, so i don't think, even this is the case.

推荐答案

听起来你有一个终结器,基本上 - 如果你只调用一次 GC.Collect(),终结器正在完成但最终确定的对象没有被收集.

Sounds like you have something with a finalizer, basically - if you only call GC.Collect() once, the finalizers are finishing but the finalized objects aren't being collected.

这是否代表错误是另一回事.一般来说,实际上需要执行的终结器并不是一个好主意,但在你的情况下可能没问题.

Whether or not that represents a bug is a different matter. Generally it's not a good idea for there to be finalizers which actually need to be executing, but maybe it's okay in your case.

这篇关于什么情况下需要调用GC.Collect两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:什么情况下需要调用GC.Collect两次

基础教程推荐