Instead of “unmanaged resources,” think “responsibilities.” When an object is described as containing "unchanged resources", this means that:
- The class has the information and incentive necessary to do something for an external object.
- If this action is never performed, something else will not work as well as otherwise (the effects may be minor or serious).
- If the class does not perform the action, there will be nothing more.
The most common situation where a class will have responsibilities for cleaning up is when some other object is asked to reserve something (be it a file, a GDI descriptor, a lock, a memory slot, a memory block, a communication channel or something else), bye notice. If nothing says that the other entity, that the reserved thing is no longer needed, it will never allow it to use anything else.
If an object that has important responsibility for performing an action is swept away by the garbage collector before fulfilling its responsibility, the action will never be performed. There are two ways to prevent this:
- If an object implements IDisposable, "someone" (either another object or a running procedure) must be assigned to call the Dispose method before it fails. Disposal cannot be regarded as the destruction of an object, but rather to inform the object of the fulfillment of its final duties so that it can be safely left.
- Objects may ask the system to tell them when they were left before they are swept away. Although such notifications can reduce the risk that the required action will never be completed, it is dangerous to rely on them, as they often do not arrive especially timely, and in some cases may not appear at all.
Objects that provide a second approach to cleanup are called "managed resources."
source share