Create a Disposable Object

Problem

You need to create an object that frees unmanaged resources deterministically.

Solution

Implement the IDisposable pattern. Clients will call the Dispose method to release the object’s resources.

Discussion

The IDisposable interface defines a single method, called Dispose. In this method, the class will release all its unmanaged resources. For best performance, when implementing IDisposable you should follow these best practices:

  • Suppress garbage collector finalization for the object, provided it has no managed resources to release.

  • Implement a finalizer that calls your Dispose method when the object is garbage collected. That way, if your object is released without Dispose being called (a common error), the resources ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook 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.