Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# disposing IDisposable

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.

like image 776
Yippie-Ki-Yay Avatar asked Dec 01 '22 03:12

Yippie-Ki-Yay


1 Answers

It completely depends on the object in question.

There are fourfive reasons that an object might implement IDisposable:

  1. 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.

  2. It owns managed objects that are disposable.
    The objects that it owns will fall also into one of these categories; see the relevant category.

  3. 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.

  4. 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.

  5. 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.

like image 149
SLaks Avatar answered Dec 05 '22 00:12

SLaks