Since .NET has a garbage collector why do we need finalizers/destructors/dispose-pattern?

前端 未结 12 1641
粉色の甜心
粉色の甜心 2020-12-07 09:09

If I understand correctly the .net runtime will always clean up after me. So if I create new objects and I stop referencing them in my code, the runtime will clean up those

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 10:05

    The Garbage Collector will only run if the system is not under memory pressure, unless it really needs to free up some memory. That means, you can never be sure when the GC will run.

    Now, Imagine you are a Database Connection. If you let the GC clean up after you, you may be connected to the database for much longer than needed, causing weird load situation. In that case, you want to implement IDisposable, so that the user can call Dispose() or use using() to really make sure that the connection is closed ASAP without having to rely on GC which may run much later.

    Generally, IDisposable is implemented on any class that works with unmanaged resources.

提交回复
热议问题