Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can't you use SafeHandle over Finalizer/IDisposable?

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?

like image 534
ill mg Avatar asked Nov 13 '11 08:11

ill mg


2 Answers

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.

like image 105
Hans Passant Avatar answered Nov 15 '22 12:11

Hans Passant


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.

like image 30
Henk Holterman Avatar answered Nov 15 '22 13:11

Henk Holterman