Before getting to know how to implement IDisposable, must has some basic about .NET system first.
Unmanaged Code, which means the code developed outside .NET Framework is known as unmanaged code. It's not run under CLR (Common Language Runtime) such as C++ can be used to write such applications , for examples, access low level functions of the operating system. It offers the powerful features that managed code does not, and might damaging as well. Unmanaged code can be unmanged source code and unmanaged compile code, and
unmanged code is execute with the help of wrapper classes, and caution is required (doesn't be executed by CLR). It will be compiled into machine code and executed by the OS directly.
Managed Code is the code that targets to common language runtime which is under foundation of .NET Framework. Managed Code will supply necessary things for CLR to provides services such as memory management, cross-language integration, handling security, lifetime control of objects, in short, it will look after your applications. All code based on IL (Intermediate Language) executes as managed code.
Garbage Collector will clean unused resources automatically, but can still call it explicitly. It will do finalizer in destructor of each object. The process of cleaning resources are done in a finalizer thread not a main thread.
Unmanaged Resources falls into two categories:
- Resources that are wrapped in a managed class (ie Bitmap, Font etc) but still need Dispose to be called to clean them up property.
- Resources that you allocated that are representations of native resources (ie device contexts that need to be released)
The propose of using dispose is we want to free both kinds of unmanged resources. Note that for the first kind of unmanged resources, the garbage collector will take care of them when it have to clean them up. We only need to focus about true native resources that we have allocated (in case we have).