by Edward
03 March 2010 06:45
Class instances often encapsulate control over resources that are not managed by the runtime such as database connections, console app window handlers, etc. Therefore, you should provide both an explicit and an implicit way to free those resources.
Dispose() is called by the user. It serves as the same purpose as finalize() - to free unmanaged resources. However, you should implement this when you are writing a custom class, that will be used by other users. Overriding Dispose() provides a way for the user code to free the unmanaged objects in your custom class.
Finalize() is called by the runtime. It is a destructor, called by the Garbage Collector(GC) when the object goes out of scope. Implement it when you have unmanaged resources in your code, and want to make sure that these resources are freed when the Garbage collection happens.
Note that even when you provide explicit control by way of Dispose(), you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose.