Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

.net - Under what circumstances, we need to call GC.Collect twice

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.

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(); 

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.

Update:

There are no Finalizers defined in Class.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...