Could someone explain what might happen if you don't Dispose
some IDisposable
entity (by using
or direct Dispose
call)?
Does this always result in a memory leak and if yes, are C#
memory leaks similiar to C++
memory leaks, where they could easily lead to a crash or is C#
sandbox safer from this point of view?
Thank you.
It completely depends on the object in question.
There are fourfive reasons that an object might implement IDisposable
:
It owns native resources.
If so, it should call Dispose
in its finalizer, so all that happens if you forget to dispose it is that the native resources last longer than necessary.
If you create lots of such objects at once and don't dispose them, you may run out of native resources.
It owns managed objects that are disposable.
The objects that it owns will fall also into one of these categories; see the relevant category.
It has a long-lasting reference to itself that won't be freed naturally (eg, it handles a static
event)
The dispose method would clear this reference (eg, unregister the event handler)
If so, not calling Dispose
will cause it to last forever.
It inherits a disposable base class, such as Stream
or Component
, but doesn't actually need to be disposed. (eg, MemoryStream
)
If so, not calling Dispose
is harmless, unless the class changes in the future.
It performs some action in its Dispose
method that people should call in a using
statement (eg, using (Html.BeginForm() { ... }
)
If so, not disposing the object will defeat its entire purpose, which is to do that action.
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