What are ways to solve Memory Leaks in C#

前端 未结 10 1761
生来不讨喜
生来不讨喜 2021-02-14 14:50

I\'m learning C#. From what I know, you have to set things up correctly to have the garbage collector actually delete everything as it should be. I\'m looking for wisdom learn

10条回答
  •  死守一世寂寞
    2021-02-14 15:47

    The best way to ensure that objects get deleted, or in .NET lingo, garbage-collected, is to ensure that all root references (references that can be traced through methods and objects to the first method on a thread's call stack) to an object are set to null.

    The GC cannot, and will not, collect an object if there are any rooted references to it, no matter whether it implements IDisposable or not.

    Circular references impose no penalty or possibility of memory leaks, as the GC marks which objects it has visited in the object graph. In the case of delegates or eventhandlers it may be common to forget to remove the reference in an event to a target method, so that the object that contains the target method can't be collected if the event is rooted.

提交回复
热议问题