Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should IDisposable.Dispose() be made safe to call multiple times?

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.

like image 554
Jake Petroules Avatar asked Mar 15 '11 02:03

Jake Petroules


People also ask

What happens if you dont Dispose IDisposable?

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.

What will happen if we call Dispose () method directly?

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.

How do you Dispose of IDisposable?

If you don't use using , then it's up to you (the calling code) to dispose of your object by explicitely calling Dispose().

Should I call Dispose C?

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.


1 Answers

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.

like image 100
Adam Robinson Avatar answered Sep 21 '22 06:09

Adam Robinson