3 ms·
They are an artifact from .Net 1.0. They allowed developers to clean up native resources (file handles, satellite links, etc.) that they might have been wrappin
by zamalek 12y ago
They are an artifact from .Net 1.0. They allowed developers to clean up native resources (file handles, satellite links, etc.) that they might have been wrapping.
.Net 2.0 introduced something called SafeHandle. SafeHandle inherits CriticalFinalizerObject which triggers special GC treatment of the finalizer. SafeHandle does a bunch of work to help you write a safe wrapper for an unmanaged/native handle.
You should almost never see a finalizer in modern C# code (there are extremely rare exceptions). Notice that the MSDN page for the dispose pattern[2] has [finally] been updated to omit the finalizer. The dispose pattern is the preferred way to do deterministic resource cleanup (in combination with SafeHandle for native resource cleanup). In .Net finalizers are now the wrong tool for the job in the majority of situations.
Another thing not mentioned in the article is that if you implement a finalizer your code becomes multithreaded. Once you have a finalizer your disposer needs to become thread-safe (and lock-free, you must never use a mutex in a finalizer). Finalizers are bad. Stay away from them.
[1]: http://blogs.msdn.com/b/bclteam/archive/2006/06/23/644343.aspx http://blogs.msdn.com/b/bclteam/archive/2006/06/23/644343.as...
[2]: https://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx https://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx