Alan
Alan

Reputation: 33

Why winform Dispose method is missing 'detect redundant calls'?

Why winform Dispose method is missing 'detect redundant calls'?

Winform now Dispose method:

   protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

Why not this?

    private bool disposedValue = false; //To detect redundant calls
    protected override void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing && (components != null))
            {
               components.Dispose();
            }

            base.Dispose(disposing);

            disposedValue = true;
        }
    }

Upvotes: 0

Views: 148

Answers (2)

Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

You need to have a disposedValue or other mechanism only if you have your own elements to free, managed or unmanaged does not matter.

If the only work you do on Dispose is to call other's Dispose you don't need to do anything as they will allow reentrancy (if they are correctly implemented).

So in this particular case you wrote you don't need to use the 'disposedValue' flag.

Having said that the most common implementation patterns for Dispose contains such flag (as a protected property to be able to use it from inheritors).

Upvotes: 0

user743382
user743382

Reputation:

There are two reasonable positions to take.

  • Dispose can be called twice. This is supported by the documentation and suggests there is no need for your disposedValue check.

  • Dispose should not be called twice. But then the form should not be disposed twice either, and if it's not, there is equally no need for your disposedValue check.

A disposedValue check inside Dispose only makes sense if some child object has a buggy implementation of Dispose that you want to work around.

Upvotes: 3

Related Questions