C#: In what cases should you null out references?

后端 未结 3 1016
情话喂你
情话喂你 2021-02-14 05:39

The CLR Profiler can also reveal which methods allocate more storage than you expected, and can uncover cases where you inadvertently keep references to useless o

相关标签:
3条回答
  • 2021-02-14 06:25

    It's important if you have long lived objects (like the cache example in your quote) holding references to short lived objects (like the cache items). Other examples of long lived objects could be singleton objects, the Main Form instance in a Windows Forms application, the Application instance of a ASP.NET application etc.

    I would like to add a another common pitfull: short lived objects subscribing to events published by long lived objects. As the event publisher holds a reference to all subscribers, the subscribers (like e. g. ASP.NET page or control instances that are needed only for milliseconds) won't be collected if you do not unsubscribe.

    0 讨论(0)
  • 2021-02-14 06:36

    You only need to do it when the variable holding the reference is going to stay "alive" but you don't want the reference itself to prevent garbage collection. In other words, if object A holds a reference to object B, and you don't need B any more but A will stay alive for other reasons. Another common example is static variables, which are "alive" for as long as the AppDomain is.

    For local variables it's almost never needed, because the GC can detect the last possible point in code where a variable will be accessed. However, if you use a variable declared outside a loop during the first iteration, but you know you won't need it for subsequent iterations, you could set that to null to help the object to become eligible for GC earlier.

    In my experience it's very rare to find myself in this situation. I hardly ever deliberate set variables to null for the sake of the GC. Usually all the member variables within an object are "useful" until the object itself becomes eligible for GC. If you find yourself with member variables which aren't useful for the whole lifetime of the object, you might want to see whether that indicates a problem with the design.

    0 讨论(0)
  • 2021-02-14 06:40

    You should null out references for object you don't need anymore when you know they won't be garbage collected otherwise.

    If you have Effective Java book, look at Item 5, there is an example of a stack implementation that has memory leaks because the objects references are not nulled out. If you don't have that book, you can look that part on Google Books here.

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