December 2007
Intermediate to advanced
896 pages
19h 57m
English
Your class references unmanaged resources and needs to ensure proper cleanup before it goes away.
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) ...Read now
Unlock full access