C#中的安全处理

时间:2020-03-06 14:57:22  来源:igfitidea点击:

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

解决方案

我认为MSDN的定义很明确:

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.

另一种看待它的方式:使用SafeHandle,我们几乎永远不需要编写另一个终结器。