Why call Dispose()? Memory leak won't occur?

前端 未结 7 746
无人及你
无人及你 2020-12-29 10:01

Edit: My question isn\'t getting the main answer that I was looking for. I wasn\'t clear. I would really like to know two things:

  1. Can NOT call
7条回答
  •  没有蜡笔的小新
    2020-12-29 10:37

    While some other answers seem to be suggesting that you can get away with not calling it, this is really bad advice. You should always call Dispose on any IDisposable resource.

    Some .NET objects have what's called a "finalizer" - something you can define on your own classes as well, but that you rarely see done in a typical C# programmer's code. The finalizer is what runs when the garbage collector destroys the object, and sometimes it will call Dispose - but only if the implementer of the class made it that way.

    The best practice is to always Dispose - no matter what. There are plenty of libraries I've used where not calling Dispose on a resource results in a memory leak, a connection leak, a operating system resource leak, or other kinds of horribleness. And the garbage collector will not reconcile the problem, because they don't implement any custom finalizer.

    See related: Will the Garbage Collector call IDisposable.Dispose for me?

提交回复
热议问题