开发者

Any sense to set obj = null(Nothing) in Dispose()?

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?
        }
    }
}


Personally I tend to; for two reasons:

  • it means that if somebody has forgotten to release the 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.
    • I really don't like accidentally keeping an entire object graph hanging around just because the user forgot to unhook one event; IDisposable is a handy "almost-kill" switch - why not detach everything available?
  • more importantly, I can cheekily now use this field to check (in methods etc) for disposal, throwing an 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.


It's just about useless. Setting to NULL back in the old COM/VB days, I believe, would decrement your reference count.

That's not true with .NET. When you set bar to null, you aren't destroying or releasing anything. You're just changing the reference that bar points to, from your object to "null". Your object still exists (though now, since nothing refers to it, it will eventually be garbage collected). With few exceptions, and in most cases, this is the same thing that would have happened had you just not made Foo IDisposable in the first place.

The big purpose of IDisposable is to allow you to release unmanaged resources, like TCP sockets or SQL connections, or whatever. This is usually done by calling whatever cleanup function the unmanaged resource provides, not by setting the reference to "null".


This can make sense if you want to somehow prevent the disposed owned instance to be re-used.

When you set references to disposable fields to null, you are guaranteed to not use the instances any more.

You will not get ObjectDisposedException or any other invalid state caused by using owned disposed instance (you may get NullReferenceException if you do not check for nulls).

This may not make sense to you as long as all IDisposable objects have a IsDisposed property and/or throw ObjectDisposedException if they are used after they are disposed - some may violate this principle and setting them to null may prevent unwanted effects from occuring.


In C# setting an object to null is just release the reference to the object.

So, it is theoretically better to release the reference on managed objects in a Dispose-Method in C#, but only for the possibility to the GC to collect the referenced object before the disposed object is collected. Since both will most likely be collected in the same run, the GC will most propably recognize, that the referenced object is only referenced by a disposed type, so both can be collected.

Also the need to release the reference is very small, since all public members of your disposable class should throw an exception if the class is alreay disposed. So no access to your referenced object would success after disposing the referenced method.


In VB.NET there is sense to set to Nothing declared Private WithEvents objects.

The handlers using Handles keyword will be removed in this way from these objects.


The purpose of the dispose() is to cleanup the resources that are unmanaged. TCP connections, database connections and other database objects and lots of such unmanaged resources are supposed to be released by the developer in the dispose method. So it really makes sense.


In general no need to set to null. But suppose you have a Reset functionality in your class.

Then you might do, because you do not want to call dispose twice, since some of the Dispose may not be implemented correctly and throw System.ObjectDisposed exception.

private void Reset()
{
    if(_dataset != null)
    {
       _dataset.Dispose();
       _dataset = null;
    }
    //..More such member variables like oracle connection etc. _oraConnection
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜