4.8. Mastering Finalize Semantics: IDisposable

Garbage collection solves an important problem: that of automatically managing the allocation and freeing up objects on the heap. But that solution introduces the smaller problem of deterministic finalization. What this means in a very broad sense is that we cannot predict when (or if) an object is finalized by the garbage collector.

One case in which the time of finalization matters occurs when a class object acquires unmanaged resources, such as a window or file handle or a database connection—resources that we don't want tied up too long, or at least no longer than necessary. What we would like, ideally, is to have such a resource freed automatically after a last use of the object holding it. ...

Get C# Primer: A Practical Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.