Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

Dispose and Close Methods

Implementing a finalizer gives your type an opportunity to release any external unmanaged resources (such as database connections or file handles) that it may be holding onto. From the perspective of the users of your type, this makes the resource management implicit: they interact with your type, and your type interacts with the resource as needed. However, since GC happens asynchronously and there are no guarantees as to exactly when the finalizers will be called, this level of control may not be sufficient. In these cases, it is good practice to also offer clients explicit resource management controls.

To provide explicit resource management to clients of your type, implement the IDisposable interface. This offers clients a Dispose( ) method they can call to explicitly instruct you to release resources. For types in which Dispose( ) doesn’t make sense, provide an explicit Close( ) method that optionally forwards to a private implementation of IDisposable.Dispose. If your type also has a finalizer (via a C# destructor), your Dispose( ) or Close( ) implementation should include a special call to the static SuppressFinalize( ) method on the System.GC type to indicate that the destructor no longer needs to be called. Typically, the real finalizer is written to call the Dispose/Close method, as follows:

using System; public class Worker : IDisposable { int id; public Worker(int id) { this.id = id; } // ... protected virtual void Dispose(bool disposing) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# in a Nutshell

C# in a Nutshell

Ben Albahari, Ted Neward, Peter Drayton
C# 7.0 in a Nutshell

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Joe Mayo

Publisher Resources

ISBN: 0596005261Catalog PageErrata