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

前端 未结 4 2153
离开以前
离开以前 2020-12-01 11:33

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 manu

相关标签:
4条回答
  • 2020-12-01 11:58

    You have a weak reference that you expect to be set to null, as you call GC and you believe that nothing is keeping the object alive.

    I don’t know how weak references are implemented in .net, but it is very possible they delay the collection of objects and makes use of a system like finalizerrs.

    Or it could be you have a object that needs to be finalized, as you have not call dispose() on it. (Very common with WPF or WinForms)

    To find out, you need to use a MemoryProfiler, expect to spend at least a day leaning how to use any memory profiler, as you will be presented with a lot of data about objects internal to WPF. Personally I would download a free trail of Redgate’s memory profiler and have a go at seeing what the problem is, there support is also helpful. (Other memory profilers also work well, to a large extend it just depends on what you are used to.)

    0 讨论(0)
  • 2020-12-01 12:09

    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.

    0 讨论(0)
  • 2020-12-01 12:14

    @Nitin, I am not sure whether my suggestion would help you or not, but as a rule of thumb we should avoid explicitly calling GC.Collect(). because it will likely to cause performance problem. Instead try to follow the proper disposal pattern.

    0 讨论(0)
  • 2020-12-01 12:17

    If i call GC.Collect only one time, its reference still remains in memory for sometime.

    Not really strange. When an object has a Finalizer (and no GC.SuppressFinalize() has been called on it), it gets a stay of execution (it is not collected, so that the finalizer can run with valid objects). All instances referenced by this object also get a stay of execution. A second round through the GC is needed to clean it all up.

    On the other hand, most programs, inlcuding big and complex ones, should be able to run without calling GC.Collect() even once. And you want to call it twice...

    after each project life cycle we do a manual Tear Down

    Sounds complicated and easy to avoid... How many refernces are there into your Domain/View models? Ideally you would just cut 1 or 2 references to a 'main' object and forget about it.

    0 讨论(0)
提交回复
热议问题