none
Memory leaks if I do not call garbage collection at app start RRS feed

  • Question

  • The application has a class with a finalizer (CF).
    CF refers to instances of class C1.
    An instance of class C2 refers to an instance of class C1.
    Finalizer of CF removes the reference from C2 to C1.

    When the application starts, a large number of C2 objects are created. They are needed throughout the application executing.
    Then the following cycles occur periodically:
    1) A large number of CF and C1 objects are created.
    2)
    Links to CF objects are removed

    After each cycle, CF objects are not unloaded from memory, their finalizers are not called.
    The application crashes when it reaches memory usage about 3.37 Gb.
    BUT! If I call

    GC.Collect();

    before starting the cycles, THERE IS NO THE MEMORY LEAK.
    During cycles, the call of GC.Collect(); has no effect.


    If I don’t call code above
    , JetBrains dotMemory Profiler shows that all the CF objects are accessible only from the f-reacheble queue.

    This behavior is stable and reproducible.
    Screenshots of 2 profiling sessions (with leak and without one) here.

    Saturday, June 13, 2020 2:51 PM

All replies

  • "CF refers to instances of class C1."
    "Finalizer of CF removes the reference from C2 to C1."

    this doesn't sound logical. The finalizer of CF should null the reference to C1.
    also.: when a class uses a finalizer, it should also implement IDispose and give you a way to cleanup deterministically.

    btw: is there a reason CF has a finalizer? are there any native resources to clean up?
    Saturday, June 13, 2020 6:07 PM
  • CF and С1 objects can be unloaded from memory, while С2 objects stay loaded.

    C2 is a class with an event. C1 contains a handler subscribed to that event. Finalizer of CF makes unsubscription C1's handler from C2's event. I want to make that unsubscription in the finalizer thread to improve performance of main thread.

    Of course, I can create my own thread that will explicitly call the code of CF's finalizer, but I want to understand the reasons for the strange behavior I described above.

    Saturday, June 13, 2020 7:06 PM
  • Hi Igor Buchelnikov,

    Thanks for your feedback.

    >>Finalizer of CF makes unsubscription C1's handler from C2's event

    Object finalization is a complex and an error-prone operation, you can consider using other substitutes.

    1. Explicit release of resources
    2. Window.Closing Event

    Best Regards,

    Xingyu Zhao



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Monday, June 15, 2020 8:22 AM
    Moderator