Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

c# - 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?
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...