Disposal Before Collection: IDisposable

Finalizers are typically implemented to ensure resources that are beyond the garbage collector’s domain of responsibility get cleaned up properly. A good example is when you must deal with unmanaged resources (for example, in Win32 interop scenarios requiring manual release of object using calls to CloseHandle). Although lots of Win32 APIs have been wrapped in the .NET Framework, you might sometimes need to P/Invoke some other APIs manually. For instance, consider the CreateJobObject Win32 function, which allows for the creation of jobs, which are groups of processes. A managed code wrapper could look like this:

public class Job{    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.