O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.36. Disposing of Unmanaged Resources

Problem

Your class references unmanaged resources such as some type of handle, or it manipulates a block of memory or a file via P/Invoke methods or your class uses a COM object that requires some cleanup method to be called before it is released. You need to make sure that the resources are released properly and in a timely manner. In a garbage-collected environment, such as that used by the Common Language Run-time (CLR), you cannot assume either will happen.

Solution

Implement the dispose design pattern, which is specific to .NET. The class that contains a reference to the unmanaged resources is shown here as Foo. This object contains references to a COM object called SomeCOMObj, a FileStream object called FStream, and an ArrayList that may or may not contain references to unmanaged resources. The source code is:

using System; using System.Collections; using System.IO; [DllImport("Kernel32.dll", SetLastError = true)] private static extern IntPtr CreateSemaphore(IntPtr lpSemaphoreAttributes, int lInitialCount, int lMaximumCount, string lpName); [DllImport("Kernel32.dll", SetLastError = true)] private static extern bool ReleaseSemaphore(IntPtr hSemaphore, int lReleaseCount, out IntPtr lpPreviousCount); public class Foo : IDisposable { public Foo( ) {} // Replace SomeCOMObj with your COM object type private SomeCOMObj comObj = new SomeCOMObj( ); private FileStream fileStream = new FileStream(@"c:\test.txt", FileMode.OpenOrCreate); private ArrayList ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required