Should implementations of IDisposable
make Dispose()
safe to call multiple times? Or the opposite? What approach to most .NET Framework classes take?
Specifically, is it safe to call System.Data.Linq.DataContext.Dispose()
multiple times?
The reason I ask is because I am wondering if this extra protection is necessary:
public override void Dispose(bool disposing) { // Extra protection... if (this.obj != null) { this.obj.Dispose(); this.obj = null; } // Versus simply... this.obj.Dispose(); base.Dispose(disposing); }
when disposing IDisposable
members of a class, or whether I should just call this.obj.Dispose()
without concern for whether it has been previously called.
IDisposable is usually used when a class has some expensive or unmanaged resources allocated which need to be released after their usage. Not disposing an object can lead to memory leaks.
The Dispose() methodThe Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.
If you don't use using , then it's up to you (the calling code) to dispose of your object by explicitely calling Dispose().
Rule of thumb: if a class implements IDisposable you should always call the Dispose method as soon as you have finished using this resource. Even better wrap it in a using statement to ensure that the Dispose method will be called even if an exception is thrown: using (var reader = conn.
You should be safe to call it more than once, though you should probably avoid it if you can.
From the MSDN page on IDisposable.Dispose()
:
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.
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