Thursday, February 23, 2006

Dispose pattern in C#.

I reviewed some chapters on the dispose pattern on Jeff's book. I really enjoyed reading this book, everytime I read it, it gave me some new thoughts.

A couple of points :

1. If you class has unmanaged resources, you have to implement IDispose pattern to ensure that resources are cleaned up properly. The GC only takes care of the memory, not the other nasty resources issues.

2. The way to implement it:
2-a. Implement a private/protecte methods like Dispose(bool disposing), if the disposing is true, you can access both managed resources which are not collected by GC yet and unmanaged resources. If it's set to false, you cannot access other managed resources since they have the possiblity to have been collected by GC already.
2-b. Implement a Dispose() method, and call Disposing(true), since we are sure it's an explicitly cleaning up.
2-c. Implement a Dispose() method optianlly,and call Disposing(true), since we are sure it's an explicitly cleaning up.
2-d. Implement the finalize() method, and call Disposing(false) . In C#, this finalize method is implemented as a destructor format, though it's not a destructor by any means.

No comments: