Search code examples
idisposableresource-leak

What are the consequences for leaking resources?


Obviously, we should clean up after ourselves as a matter of principle. And those of us around before the Windows 2000 era know the pain that memory leaks inflict on users. But I'm curious as to what the consequences of leaking handles to other system resources might be.

This would be things like unclosed files or database connections. Really anything that would be IDisposable in .net. We're a Windows shop, but I would be interested in other OSes as well.

What arguments can I use to get team members to take this more seriously, or are there bigger fish to fry on modern systems?


Solution

  • Instead of thinking of resources as "things" to be "released", it's better to think of the acquisition of an IDisposable object a responsibility to be carried out. Many kinds of IDisposable objects ask outside entities to do things on their behalf until they notify those entities that their services are no longer needed; by so doing, they acquire a responsibility to ensure that those outside entities are in fact given such notice. When Dispose is called on an IDisposable, it can carry out its responsibility to notify anything whose services it had been using that those services are no longer required.

    Objects can request notification if the system notices that they've been abandoned. Objects that receive such notification can then generally assume that their services are no longer needed, and notify anyone whose services that they had been using of that. This mechanism works okay in some cases, but it should not be considered reliable, since a variety of factors may prevent the system from noticing that an object has been effectively abandoned.

    As for the consequence of failing to call Dispose, it's very simple: things that were supposed to happen as a consequence of an object's services no longer being required, won't happen. If an object was supposed to notify other objects or entities that their services are no longer required, and they were in turn supposed to notify other objects or entities, none of those notifications will happen.

    Except in a few cases where code will be using a managed resource for the life of the program, and the OS can be relied upon to recognize termination of the program as an indication that the program no longer needs its services, it will generally be easier to call Dispose on things that are no longer needed, whether or not they really "care", than to try to identify the cases where major problems would be caused by the resulting failures of entities to notify everything that care that their services are no longer needed.