Is there any sense to set custom object to null
(Nothing
in VB.NET) in the Dispose()
method? Could this prevent memory leaks or it's useless?!
Let's consider two examples:
public class Foo : IDisposable { private Bar bar; // standard custom .NET object public Foo(Bar bar) { this.bar = bar; } public void Dispose() { bar = null; // any sense? } } public class Foo : RichTextBox { // this could be also: GDI+, TCP socket, SQl Connection, other "heavy" object private Bitmap backImage; public Foo(Bitmap backImage) { this.backImage = backImage; } protected override void Dispose(bool disposing) { if (disposing) { backImage = null; // any sense? } } }
When an object implements IDisposable you should call Dispose (or Close , in some cases, that will call Dispose for you). You normally do not have to set objects to null , because the GC will know that an object will not be used anymore.
The dispose pattern is used for objects that implement the IDisposable interface, and is common when interacting with file and pipe handles, registry handles, wait handles, or pointers to blocks of unmanaged memory. This is because the garbage collector is unable to reclaim unmanaged objects.
Dispose() will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector.
You should take advantage of the Dispose/Finalize pattern only when it is needed. To be more precise, you should use it only when your type invokes unmanaged code that allocates unmanaged resources (including unmanaged memory) and then it returns a handle that you must use eventually to release the resource.
Personally I tend to; for two reasons:
Foo
(perhaps from an event) any downstream objects (a Bitmap
in this case) can still be collected (at some point in the future - whenever the GC feels like it); it is likely that this is just a shallow wrapper around an unmanaged resource, but every little helps. IDisposable
is a handy "almost-kill" switch - why not detach everything available?ObjectDisposedException
if it is null
The purpose of Dispose()
is to allow clean up of resources that are not handled by the garbage collector. Objects are taken care of by GC, so there's really no need to set the reference to null under normal circumstances.
The exception is if you expect the caller to call Dispose
and hold on to the instance after that. In that case, it can be a good idea to set the internal reference to null. However, disposable instances are typically disposed and released at the same time. In these cases it will not make a big difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With