的SafeHandle在C#SafeHandle

2023-09-04 09:38:30 作者:╰回憶總是殇

什么是SafeHandle的?它是如何从IntPtr的有什么不同?什么时候应该使用一个?它有什么优势?

What is SafeHandle? how does it differ from IntPtr? When should I use one? What are its advantages?

推荐答案

我觉得MSDN为pretty的明确定义:

I think MSDN is pretty clear in definition:

本的SafeHandle类提供关键   终结处理资源,   被preventing处理   回收prematurely垃圾   收集和再循环由   Windows以参考意外   非托管对象。在.NET之前   Framework 2.0版,所有操作   系统处理只能是   封装在管理中的IntPtr   包装对象。

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.

本的SafeHandle类包含一个   终结器,确保在手柄   被关闭并且保证运行,   即使在意外的AppDomain   卸载时,主机可能不信任   的状态的一致性   AppDomain中。

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.

有关的更多信息   使用的SafeHandle的好处,看   安全把手和关键   定稿。

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

这是一个抽象类,因为你   不能创建一个通用的手柄。至   实施的SafeHandle,必须创建   派生类。要创建的SafeHandle   派生类,你必须知道如何   创建和释放一个操作系统   处理。该过程用于不同   不同的手柄类型,因为一些   使用CloseHandle的,而另一些使用更   具体的方法如   UnmapViewOfFile或FindClose。为了这   因此,必须创建一个派生   每个工作类的SafeHandle的   系统手柄式;例如   MySafeRegistryHandle,   MySafeFileHandle,和   MySpecialSafeFileHandle。其中的一些   派生类是prewritten和   在为您提供   Microsoft.Win32.SafeHandles命名空间。

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.