3.17. Disposing of Unmanaged Resources

Problem

Your class references unmanaged resources and needs to ensure proper cleanup before it goes away.

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 shown in Example 3-8.

Example 3-8. Foo: A class that contains references to unmanaged code

using System;
using System.Collections;
using System.IO;
using System.Runtime.InteropServices;

public class Foo : IDisposable
{
     [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 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 aList = new ArrayList( );
      private bool hasBeenDisposed = false;
      private IntPtr hSemaphore = IntPtr.Zero; // Unmanaged handle

      // Protect these members from being used on a disposed object. public void WriteToFile(string text) { if(hasBeenDisposed) ...

Get C# 3.0 Cookbook, 3rd Edition 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.