ASP.Net SafeHandle - tasks and examples

55 Views Asked by At

I want to understand how to work with unmanaged resources and when I need the SafeHandle class. What can be the problem statement when you can say: "Oh, here I need the SafeHandle class!"?

I would be grateful for links to articles, examples, explanations

1

There are 1 best solutions below

1
On

I think MSDN is pretty clear in definition:

The SafeHandle class provides critical finalization of handle resources, preventing handles from being reclaimed prematurely by garbage collection and from being recycled by Windows to reference unintended unmanaged objects. Before the .NET Framework version 2.0, all operating system handles could only be encapsulated in the IntPtr managed wrapper object.

The SafeHandle class contains a finalizer that ensures that the handle is closed and is guaranteed to run, even during unexpected AppDomain unloads when a host may not trust the consistency of the state of the AppDomain.

For more information about the benefits of using a SafeHandle, see Safe Handles and Critical Finalization.

This class is abstract because you cannot create a generic handle. To implement SafeHandle, you must create a derived class. To create SafeHandle derived classes, you must know how to create and free an operating system handle. This process is different for different handle types because some use CloseHandle, while others use more specific methods such as UnmapViewOfFile or FindClose. For this reason, you must create a derived class of SafeHandle for each operating system handle type; such as MySafeRegistryHandle, MySafeFileHandle, and MySpecialSafeFileHandle. Some of these derived classes are prewritten and provided for you in the Microsoft.Win32.SafeHandles namespace.