
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Disposing of Unmanaged Resources
|
207
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,aFileStream
object called FStream, and an ArrayList that may or may not contain references to
unmanaged resources. The source code is shown in Example 3-23.
Example 3-23. 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 ...