-1

Should it be possible, to call .Dispose for the same instance of IDisposable multiple times without throwing an exception? Is there some definition for this?

For example:

public class Test : IDisposable
{
    public void Dispose()
    {
        // What ever
    }
}

var t = Test();
t.Dispose();
t.Dispose(); // Should this work in any case?

The reason why I'm asking this:

I've created some mechanism, which search in the VisualTree for elements, which inherit from IDisposable, but i can not be sure, that one of these elements gets disposed before.

Some code snipped from a window class

/// <summary>
/// Dispose
/// </summary>
public void DisposeAll()
{
    foreach (var obj in WPFVisualTreeHelper.FindChildren<IDisposable>(this))
    {
        if (!disposables.Contains(obj))
        {
            disposables.Add(obj);
        }
    }
    foreach (IDisposable disposable in disposables)
    {
        disposable.Dispose();
    }
}

Thank you!

Mostafiz
  • 7,243
  • 3
  • 28
  • 42
BendEg
  • 20,098
  • 17
  • 57
  • 131
  • 4
    IIRC the guidelines for IDisposable state that multiple calls to `Dispose` should not throw. I'll see if I can find a reference. – spender Apr 21 '16 at 08:49
  • Oh thianks, that would be nice! – BendEg Apr 21 '16 at 08:50
  • 1
    BTW, if you're not [making your classes `sealed`](http://stackoverflow.com/questions/11024336/why-does-sealed-affect-the-implementation-of-idisposable) then you should implement the full [basic dispose pattern](https://msdn.microsoft.com/en-us/library/b1yfkh5e%28v=vs.110%29.aspx#basic_pattern) (so that `Dispose` doesn't break when the class is extended). – spender Apr 21 '16 at 08:55

2 Answers2

1

If an object's Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.

Source

Draken
  • 3,134
  • 13
  • 34
  • 54
1

MSDN says:

The object must not throw an exception if its Dispose method is called multiple times. Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.

The last part is also important: make sure to set a disposed boolean flag to ensure resources aren't used after Dispose is called. You can also use that for the second call to Dispose to just ignore it.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325