When seeing about the whole finalizer/IDisposable issue, it is usual to see that, at the end, after all the long description, there will be something to the meaning of "LOL what I said was actually useless, you should use SafeHandle instead bye!" So I am wondering in what case does SafeHandle not fit, such that you have to resort to the finalizer/IDisposable old way?
Clearly, when the unmanaged resource you are wrapping is not acquired through a handle. Which is rare but not unheard of. An example would be writing wrappers in C++/CLI code, commonly done to wrap a native C++ class. The resource is then memory. The unmanaged kind.
Nevertheless, you can spend a career writing managed code and never write a finalizer. Finalizers belong in the framework classes.
When can't you use SafeHandle over Finalizer/IDisposable?
The obvious answer is almost never, Safehandles offer a lot of advantages.
But the code inside ReleasHandle()
must confirm to the constraints of a Constrained Execution Region (CER) . It can (should) not call code that could throw or lock. So if your cleanup is more complicated and 'unreliable' you still have to use a Finalizer/destructor.
But for (OS) handles you can and should always use a SafeHandle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With