Why call Dispose()? Memory leak won't occur?

前端 未结 7 732
无人及你
无人及你 2020-12-29 10:01

Edit: My question isn\'t getting the main answer that I was looking for. I wasn\'t clear. I would really like to know two things:

  1. Can NOT call
7条回答
  •  借酒劲吻你
    2020-12-29 10:47

    Can NOT calling Dispose() cause memory leaks?

    Yes, of course. Below is just one example.

    Assume you have a main window in your application and you create a child control that has an event subscription to the main window. You unsubscribe from them on Dispose. If you don't dispose, main window can hold the reference to your child control until you close the application.

    What's the worst thing that can happen if you have a large program and never call Dispose() on any of your IDisposable objects?

    The worse case is not releasing some unwanted memory until you close the application.

    And the other question is, what if you never implement IDisposable or finalization when they are required?

    The worse case of having a memory leak is holding on to that memory until you restart the PC. This can happen only if you have un-managed resources and you don't implement dispose/finalize. If you implement Idisposable interface and implement the finalizer, finalization process will execute the Dispose for you.

    Another reason why you should call Dispose is to Suppress the finalization.

    As I've indicated before if there is any object with Finalize method and you didn't call the Dispose. That object can reside in memory for two GC cycles. In the first cycle, it enqueue that instance to the finalization queue and finalization happens after GC process. So, only next GC cycle can release that memory.

提交回复
热议问题