Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage Collection: Is it necessary to set large objects to null in a Dispose method?

Is it necessary to set large objects to null when implementing a Dispose() method?

like image 950
joek1975 Avatar asked Sep 08 '08 15:09

joek1975


People also ask

Do null objects require garbage collection?

Not necessarily. An object becomes eligible for garbage collection when there are no live threads anymore that hold a reference to the object. Explicit nulling is simply the practice of setting reference objects to null when you are finished with them.

What will happen if we call Dispose () method directly?

The Dispose() methodThe Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.

What happens if Dispose is not called?

If Dispose is not called, the Finalize method should be implemented. After calling the Dispose method, the GC. SuppressFinalize method must be called to avert the Finalize method and avoid unnecessary GC. Exceptions should be carefully handled if the Dispose method is invoked more than once.

When should I use dispose?

The Dispose Method—Explicit Resource Cleanup Unlike Finalize, developers should call Dispose explicitly to free unmanaged resources. In fact, you should call the Dispose method explicitly on any object that implements it to free any unmanaged resources for which the object may be holding references.


1 Answers

Not usually.

The garbage collector looks for rooted objects, and circular dependencies don't prevent collection if neither object is rooted.

There is a caveat: if object A has a reference to object B, and object B is being disposed, you may want to clean up that relationship or else you could end up with a leak. The most common place this surfaces is in event handlers (the reference from A->B is one that B controls, because it subscribed to an event on A). In this case, if A is still rooted, B cannot be collected even though it's been disposed.

like image 66
Brad Wilson Avatar answered Sep 22 '22 12:09

Brad Wilson