在什么情况下,我们需要调用GC.Collect两次两次、情况下、GC、Collect

2023-09-02 10:31:21 作者:美友

我们有一个WPF应用程序的基础上,团结MMVVVM格局。在应用程序生命周期可以有几个项目的生命周期,每一个项目的生命周期之后,我们做了人工拆除,并尝试释放的ViewModels的所有参考。对于事件的订阅与统一,我们使用的是弱引用。因此,我们假设推倒之后,我们可以称之为GC收集,使所有的垃圾对象是垃圾收集。我们有手动取消订阅的所有事件的另一种选择,但我们是preferring垃圾收集,因为它会清除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();

任何想法或指针就会有强烈的AP preciated。

Any thoughts or pointers will be highly appreciated.

更新:

有没有在类中定义终结。

There are no Finalizers defined in Class.

现在我也在考虑的情况下,在该对象被称为其中可能有一个终结的另一个对象。在我们的框架,我们有终结仅供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.

无论这是否再presents的一个错误是另一回事。通常它不是有被终结,实际上必须执行一个好主意,但也许它的好你的情况。

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.