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 implementIDisposable:It owns native resources.
If so, it should call
Disposein 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
staticevent)The dispose method would clear this reference (eg, unregister the event handler)
If so, not calling
Disposewill cause it to last forever.It inherits a disposable base class, such as
StreamorComponent, but doesn’t actually need to be disposed. (eg,MemoryStream)If so, not calling
Disposeis harmless, unless the class changes in the future.It performs some action in its
Disposemethod that people should call in ausingstatement (eg,using (Html.BeginForm() { ... })If so, not disposing the object will defeat its entire purpose, which is to do that action.