When Can't You Use SafeHandle Over Finalizer / IDisposable?

When you see the whole problem of the finalizer / IDisposable, it is usually seen that in the end, after all the long description, there will be something meaning "LOL, which I said is actually useless, you should use it. I hope it is safe! Therefore, I wonder in which case is SafeHandle not suitable, so you need to resort to the finalizer / IDisposable in the old way?

+4
source share
3 answers

It is clear that when the unmanaged resource that you wrap does not work through the handle. Which is rare, but not unheard of. An example would be to write wrappers in C ++ / CLI code, commonly used to port a native C ++ class. A resource is a memory. Uncontrollable view.

However, you can spend your career writing managed code and never write a finalizer. Finalizers come within the scope of classes.

+3
source

When Can't You Use SafeHandle Over Finalizer / IDisposable?

The obvious answer is almost never, Safehandles does not have a big advantage.

But the code inside ReleasHandle() should confirm the constraints of the Limited Execution Region (CER) . It may (should) not cause a code that may be thrown or blocked. Therefore, if your cleanup is more complicated and "unreliable", you still have to use Finalizer / destructor.

But for pens (OS) you can and should always use SafeHandle.

+3
source

Many types of unmanaged resources can satisfy their cleanup responsibilities by using a simple API call on the handle. Such resources can (and often should) be useful encapsulated in SafeHandle. Some other types of unmanaged resources (for example, subscriptions to events held by long-lived publishers) have cleaning responsibilities that cannot be handled with a finalizer. Finalizers can be useless if semantically useless links refer to objects left alive and may be unsuitable for resources that need to be cleared by the thread that creates them. There is no need to write a custom finalizer for such resources, because no type of finalizer will eliminate the absolute 100% need to provide a deterministic solution.

However, some types of resources may benefit from having a finalizer, even if they need to perform actions that are not allowed within the scope of the constraints. Finalizers can be useful in situations where the background thread is responsible for manipulating the object and where the main application stores the object, which, in turn, contains a link to the real object. The finalizer of the main application link binding object may signal a background thread that the object that it supports is no longer needed. Such an alarm must be done carefully to ensure that it does not break the finalizer threads, but if done with caution, it may be useful to have it in the finalizer, even if this is not permitted in CER.

0
source

Source: https://habr.com/ru/post/1380984/


All Articles