C# disposing IDisposable

后端 未结 7 2116
滥情空心
滥情空心 2021-01-14 02:44

Could someone explain what might happen if you don\'t Dispose some IDisposable entity (by using or direct Dispose cal

7条回答
  •  爱一瞬间的悲伤
    2021-01-14 03:19

    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.

提交回复
热议问题