Do you need to dispose of objects and set them to null?

前端 未结 11 1835
不思量自难忘°
不思量自难忘° 2020-11-22 10:58

Do you need to dispose of objects and set them to null, or will the garbage collector clean them up when they go out of scope?

11条回答
  •  盖世英雄少女心
    2020-11-22 11:42

    Normally, there's no need to set fields to null. I'd always recommend disposing unmanaged resources however.

    From experience I'd also advise you to do the following:

    • Unsubscribe from events if you no longer need them.
    • Set any field holding a delegate or an expression to null if it's no longer needed.

    I've come across some very hard to find issues that were the direct result of not following the advice above.

    A good place to do this is in Dispose(), but sooner is usually better.

    In general, if a reference exists to an object the garbage collector (GC) may take a couple of generations longer to figure out that an object is no longer in use. All the while the object remains in memory.

    That may not be a problem until you find that your app is using a lot more memory than you'd expect. When that happens, hook up a memory profiler to see what objects are not being cleaned up. Setting fields referencing other objects to null and clearing collections on disposal can really help the GC figure out what objects it can remove from memory. The GC will reclaim the used memory faster making your app a lot less memory hungry and faster.

提交回复
热议问题