One major point of confusion, which may not be applicable in your case but arises often, is what exactly constitutes a "resource". From the perspective of an object, an unmanaged resource is something which an outside entity () is "doing"(*) on its behalf, which that outside entity will keep doing--to the detriment of other entitites--until told to stop. For example, if an object opens a file, the machine which hosts the file may grant that object exclusive access, denying everyone else in the universe a chance to use it unless or until it gets notified that the exclusive access isn't needed anymore.
(*) which could be anything, anywhere; possibly not even on the same computer.
(**) or some way in which the the behavior or state of an outside entity is altered
If an outside entity is doing something on behalf of an object which is abandoned and disappears without first letting the entity know its services are no longer required, the outside entity will have no way of knowing that it should stop acting on behalf of the object which no longer exists. IDisposable provides one way of avoiding this problem by providing a standard means of notifying objects when their services are not required. An object whose services are no longer required will generally not need to ask any further favors from any other entities, and will thus be able to request that any entities that had been acting on its behalf should stop doing so.
To allow for the case where an object gets abandoned without IDisposable.Dispose()
having been called first, the system allows objects to register a "failsafe" cleanup method called Finalize()
. Because for whatever reason, the creators of C# don't like the term Finalize()
, the language requires the use of a construct called a "destructor" which does much the same thing. Note that in general, Finalize()
will mask rather than solve problems, and can create problems of its own, so it should be used with extreme caution if at all.
A "managed resource" is typically a name given to an object which implements IDisposable
and usually, though not always, implements a finalizer.