Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it reasonable to avoid explicit calls to Dispose()?

Tags:

c#

idisposable

Is it reasonable to make a rule against explicitly calling Dispose() on an IDisposable object?

Are there any cases where a using statement cannot properly ensure an IDisposable object is cleaned up?

like image 239
Nick Strupat Avatar asked Jan 16 '12 23:01

Nick Strupat


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.

When should I use Dispose?

The Dispose Method—Explicit Resource Cleanup The Dispose method generally doesn't free managed memory—typically, it's used for early reclamation of only the unmanaged resources to which a class is holding references. In other words, this method can release the unmanaged resources in a deterministic fashion.

Does the garbage collector call Dispose?

The Dispose() method The 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.

Is Dispose method called automatically?

Dispose method must be called explicitly, objects that implement IDisposable should also implement a finalizer to handle freeing resources when System. IDisposable. Dispose is not called. By default, the garbage collector will automatically call an object's finalizer prior to reclaiming its memory.


1 Answers

Is it reasonable to make a rule against explicitly calling Dispose() on an IDisposable object?

No.

Are there any cases where a using statement cannot properly ensure an IDisposable object is cleaned up?

There are certainly cases where it makes no sense to use using to dispose an object for you. For example, all cases where the desired lifetime of the object is not bound by a particular activation of a method containing a using statement.

Consider for example a disposable object which "takes over management" of another disposable object. The "outer" object may well be disposed by a using block, but how is the "inner" object, likely stored in a private field of the outer object, to be disposed without an explicit call to Dispose()?

like image 177
Eric Lippert Avatar answered Oct 10 '22 12:10

Eric Lippert