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 ...
Get C# 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.