System.Object.Finalize 方法

本文提供了此 API 参考文档的补充说明。

该方法 Finalize 用于在销毁对象之前对当前对象持有的非托管资源执行清理操作。 此方法受到保护,因此只能通过此类或派生类进行访问。

最终化的工作原理

Object 类没有为 Finalize 该方法提供实现,垃圾回收器不会标记派生的类型 Object 进行最终化,除非它们重写该方法 Finalize

如果某个类型确实重写 Finalize 了该方法,垃圾回收器会将该类型的每个实例的条目添加到名为“最终化队列”的内部结构中。 最终化队列包含托管堆中所有对象的条目,其最终化代码必须运行,然后垃圾回收器才能回收其内存。 然后,垃圾回收器会在以下条件下自动调用 Finalize 该方法:

  • 垃圾回收器发现对象不可访问后,除非该对象已被调用 GC.SuppressFinalize 方法免除最终化。
  • 仅在 .NET Framework 上,在关闭应用程序域期间,除非对象不受最终化的影响。 在关闭期间,甚至仍可访问的对象也会最终完成。

Finalize仅在给定实例上自动调用一次,除非使用某种机制重新注册对象,GC.SuppressFinalize否则GC.ReRegisterForFinalize该方法随后尚未调用。

Finalize 操作具有以下限制:

  • 终结器执行的确切时间未定义。 若要确保类实例的资源确定性释放,请实现方法 Close 或提供 IDisposable.Dispose 实现。
  • 即使一个对象引用另一个对象,也不能保证两个对象的终结器按任何特定顺序运行。 也就是说,如果对象 A 具有对对象 B 的引用,并且都具有终结器, 在对象 A 的终结器启动时,对象 B 可能已被终结。
  • 未指定终结器运行的线程。

此方法 Finalize 可能不会运行到完成状态,也可能根本不在以下特殊情况下运行:

  • 如果另一个终结器无限期地阻止(进入无限循环,尝试获取它永远无法获取的锁,依此类说)。 由于运行时尝试运行终结器完成,因此如果终结器无限期阻止,则可能不会调用其他终结器。
  • 如果进程终止而不让运行时有机会清理。 在这种情况下,运行时的第一个进程终止通知是DLL_PROCESS_DETACH通知。

运行时仅在可终结对象数继续减少时,才会在关闭期间完成对象。

如果 Finalize 或重写 Finalize 引发异常,并且运行时不由替代默认策略的应用程序托管,则运行时将终止进程,并且不会执行活动 try/finally 块或终结器。 如果终结器无法释放或销毁资源,则此行为可确保进程完整性。

重写 Finalize 方法

应替代Finalize使用非托管资源的类,例如文件句柄或数据库连接在垃圾回收期间卡使用它们时必须释放的托管对象。 不应为托管对象实现方法 Finalize ,因为垃圾回收器会自动释放托管资源。

重要

SafeHandle如果对象可用于包装非托管资源,建议的替代方法是使用安全句柄实现释放模式,而不是重写Finalize。 有关详细信息,请参阅保险箱Handle 备用部分。

默认情况下,该方法 Object.Finalize 不执行任何操作,但应仅在必要时重写 Finalize ,并仅释放非托管资源。 如果最终化操作运行,回收内存往往需要更长的时间,因为它至少需要两个垃圾回收。 此外,应仅重写 Finalize 引用类型的方法。 公共语言运行时仅完成引用类型。 它忽略值类型的终结器。

方法的范围 Object.Finalizeprotected. 重写类中的方法时,应保留此有限范围。 通过保护 Finalize 方法,可以阻止应用程序的用户直接调用对象的 Finalize 方法。

派生类型的每个实现 Finalize 都必须调用其基类型的实现 Finalize。 这是允许应用程序代码调用 Finalize的唯一情况。 对象 Finalize 的方法不应对其基类以外的任何对象调用方法。 这是因为可以收集与调用对象相同的其他对象,例如在公共语言运行时关闭的情况下。

注意

C# 编译器不允许重写该方法 Finalize 。 而是通过为类实现 析构函数 来提供终结器。 C# 析构函数会自动调用其基类的析构函数。

Visual C++ 还提供自己的语法来实现 Finalize 该方法。 有关详细信息,请参阅如何:定义和使用类和结构(C++/CLI)“析构函数和终结器”部分。

由于垃圾回收是不确定的,因此你不知道垃圾回收器何时执行最终确定。 若要立即释放资源,还可以选择实现 释放模式IDisposable 接口。 IDisposable.Dispose类使用者可以调用实现来释放非托管资源,并且当未调用该方法时Dispose,可以使用Finalize该方法释放非托管资源。

Finalize 几乎可以采取任何操作,包括恢复对象(即,使对象在垃圾回收期间被清理后再次访问)。 但是,对象只能复活一次; Finalize 无法在垃圾回收期间对复活的对象调用。

SafeHandle 备用方法

创建可靠的终结器通常很困难,因为无法假设应用程序的状态,并且由于未经处理的系统异常(例如 OutOfMemoryExceptionStackOverflowException 终止终结器)。 可以使用派生自 System.Runtime.InteropServices.SafeHandle 类的对象来包装非托管资源,然后实现释放模式而不使用终结器实现释放模式。 .NET Framework 在命名空间中 Microsoft.Win32 提供派生自 System.Runtime.InteropServices.SafeHandle以下类:

以下示例使用具有安全句柄的 释放模式 ,而不是重写 Finalize 该方法。 它定义一个 FileAssociation 类,该类包装有关处理具有特定文件扩展名的文件的应用程序的注册表信息。 Windows RegOpenKeyEx 函数调用作为out参数返回的两个注册表句柄将传递给SafeRegistryHandle构造函数。 然后,该类型的受保护 Dispose 方法调用 SafeRegistryHandle.Dispose 该方法以释放这两个句柄。

using Microsoft.Win32.SafeHandles;
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;

public class FileAssociationInfo : IDisposable
{
   // Private variables.
   private String ext;
   private String openCmd;
   private String args;
   private SafeRegistryHandle hExtHandle, hAppIdHandle;

   // Windows API calls.
   [DllImport("advapi32.dll", CharSet= CharSet.Auto, SetLastError=true)]
   private static extern int RegOpenKeyEx(IntPtr hKey,
                  String lpSubKey, int ulOptions, int samDesired,
                  out IntPtr phkResult);
   [DllImport("advapi32.dll", CharSet= CharSet.Unicode, EntryPoint = "RegQueryValueExW",
              SetLastError=true)]
   private static extern int RegQueryValueEx(IntPtr hKey,
                  string lpValueName, int lpReserved, out uint lpType,
                  string lpData, ref uint lpcbData);
   [DllImport("advapi32.dll", SetLastError = true)]
   private static extern int RegSetValueEx(IntPtr hKey, [MarshalAs(UnmanagedType.LPStr)] string lpValueName,
                  int Reserved, uint dwType, [MarshalAs(UnmanagedType.LPStr)] string lpData,
                  int cpData);
   [DllImport("advapi32.dll", SetLastError=true)]
   private static extern int RegCloseKey(UIntPtr hKey);

   // Windows API constants.
   private const int HKEY_CLASSES_ROOT = unchecked((int) 0x80000000);
   private const int ERROR_SUCCESS = 0;

    private const int KEY_QUERY_VALUE = 1;
    private const int KEY_SET_VALUE = 0x2;

   private const uint REG_SZ = 1;

   private const int MAX_PATH = 260;

   public FileAssociationInfo(String fileExtension)
   {
      int retVal = 0;
      uint lpType = 0;

      if (!fileExtension.StartsWith("."))
             fileExtension = "." + fileExtension;
      ext = fileExtension;

      IntPtr hExtension = IntPtr.Zero;
      // Get the file extension value.
      retVal = RegOpenKeyEx(new IntPtr(HKEY_CLASSES_ROOT), fileExtension, 0, KEY_QUERY_VALUE, out hExtension);
      if (retVal != ERROR_SUCCESS)
         throw new Win32Exception(retVal);
      // Instantiate the first SafeRegistryHandle.
      hExtHandle = new SafeRegistryHandle(hExtension, true);

      string appId = new string(' ', MAX_PATH);
      uint appIdLength = (uint) appId.Length;
      retVal = RegQueryValueEx(hExtHandle.DangerousGetHandle(), String.Empty, 0, out lpType, appId, ref appIdLength);
      if (retVal != ERROR_SUCCESS)
         throw new Win32Exception(retVal);
      // We no longer need the hExtension handle.
      hExtHandle.Dispose();

      // Determine the number of characters without the terminating null.
      appId = appId.Substring(0, (int) appIdLength / 2 - 1) + @"\shell\open\Command";

      // Open the application identifier key.
      string exeName = new string(' ', MAX_PATH);
      uint exeNameLength = (uint) exeName.Length;
      IntPtr hAppId;
      retVal = RegOpenKeyEx(new IntPtr(HKEY_CLASSES_ROOT), appId, 0, KEY_QUERY_VALUE | KEY_SET_VALUE,
                            out hAppId);
       if (retVal != ERROR_SUCCESS)
         throw new Win32Exception(retVal);

      // Instantiate the second SafeRegistryHandle.
      hAppIdHandle = new SafeRegistryHandle(hAppId, true);

      // Get the executable name for this file type.
      string exePath = new string(' ', MAX_PATH);
      uint exePathLength = (uint) exePath.Length;
      retVal = RegQueryValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0, out lpType, exePath, ref exePathLength);
      if (retVal != ERROR_SUCCESS)
         throw new Win32Exception(retVal);

      // Determine the number of characters without the terminating null.
      exePath = exePath.Substring(0, (int) exePathLength / 2 - 1);
      // Remove any environment strings.
      exePath = Environment.ExpandEnvironmentVariables(exePath);

      int position = exePath.IndexOf('%');
      if (position >= 0) {
         args = exePath.Substring(position);
         // Remove command line parameters ('%0', etc.).
         exePath = exePath.Substring(0, position).Trim();
      }
      openCmd = exePath;
   }

   public String Extension
   { get { return ext; } }

   public String Open
   { get { return openCmd; }
     set {
        if (hAppIdHandle.IsInvalid | hAppIdHandle.IsClosed)
           throw new InvalidOperationException("Cannot write to registry key.");
        if (! File.Exists(value)) {
           string message = String.Format("'{0}' does not exist", value);
           throw new FileNotFoundException(message);
        }
        string cmd = value + " %1";
        int retVal = RegSetValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0,
                                   REG_SZ, value, value.Length + 1);
        if (retVal != ERROR_SUCCESS)
           throw new Win32Exception(retVal);
     } }

   public void Dispose()
   {
      Dispose(disposing: true);
      GC.SuppressFinalize(this);
   }

   protected void Dispose(bool disposing)
   {
      // Ordinarily, we release unmanaged resources here;
      // but all are wrapped by safe handles.

      // Release disposable objects.
      if (disposing) {
         if (hExtHandle != null) hExtHandle.Dispose();
         if (hAppIdHandle != null) hAppIdHandle.Dispose();
      }
   }
}
open Microsoft.Win32.SafeHandles
open System
open System.ComponentModel
open System.IO
open System.Runtime.InteropServices

// Windows API constants.
let HKEY_CLASSES_ROOT = 0x80000000
let ERROR_SUCCESS = 0
let KEY_QUERY_VALUE = 1
let KEY_SET_VALUE = 0x2
let REG_SZ = 1u
let MAX_PATH = 260

// Windows API calls.
[<DllImport("advapi32.dll", CharSet= CharSet.Auto, SetLastError=true)>]
extern int RegOpenKeyEx(nativeint hKey, string lpSubKey, int ulOptions, int samDesired, nativeint& phkResult)
[<DllImport("advapi32.dll", CharSet= CharSet.Unicode, EntryPoint = "RegQueryValueExW", SetLastError=true)>]
extern int RegQueryValueEx(nativeint hKey, string lpValueName, int lpReserved, uint& lpType, string lpData, uint& lpcbData)
[<DllImport("advapi32.dll", SetLastError = true)>]
extern int RegSetValueEx(nativeint hKey, [<MarshalAs(UnmanagedType.LPStr)>] string lpValueName, int Reserved, uint dwType, [<MarshalAs(UnmanagedType.LPStr)>] string lpData, int cpData)
[<DllImport("advapi32.dll", SetLastError=true)>]
extern int RegCloseKey(unativeint hKey)

type FileAssociationInfo(fileExtension: string) =
    // Private values.
    let ext =
        if fileExtension.StartsWith "." |> not then
            "." + fileExtension
        else
            fileExtension
    let mutable args = ""
    let mutable hAppIdHandle = Unchecked.defaultof<SafeRegistryHandle>
    let mutable hExtHandle = Unchecked.defaultof<SafeRegistryHandle>
    let openCmd = 
        let mutable lpType = 0u
        let mutable hExtension = 0n
        // Get the file extension value.
        let retVal = RegOpenKeyEx(nativeint HKEY_CLASSES_ROOT, fileExtension, 0, KEY_QUERY_VALUE, &hExtension)
        if retVal <> ERROR_SUCCESS then
            raise (Win32Exception retVal)
        // Instantiate the first SafeRegistryHandle.
        hExtHandle <- new SafeRegistryHandle(hExtension, true)

        let appId = String(' ', MAX_PATH)
        let mutable appIdLength = uint appId.Length
        let retVal = RegQueryValueEx(hExtHandle.DangerousGetHandle(), String.Empty, 0, &lpType, appId, &appIdLength)
        if retVal <> ERROR_SUCCESS then
            raise (Win32Exception retVal)
        // We no longer need the hExtension handle.
        hExtHandle.Dispose()

        // Determine the number of characters without the terminating null.
        let appId = appId.Substring(0, int appIdLength / 2 - 1) + @"\shell\open\Command"

        // Open the application identifier key.
        let exeName = String(' ', MAX_PATH)
        let exeNameLength = uint exeName.Length
        let mutable hAppId = 0n
        let retVal = RegOpenKeyEx(nativeint HKEY_CLASSES_ROOT, appId, 0, KEY_QUERY_VALUE ||| KEY_SET_VALUE, &hAppId)
        if retVal <> ERROR_SUCCESS then
            raise (Win32Exception retVal)

        // Instantiate the second SafeRegistryHandle.
        hAppIdHandle <- new SafeRegistryHandle(hAppId, true)

        // Get the executable name for this file type.
        let exePath = String(' ', MAX_PATH)
        let mutable exePathLength = uint exePath.Length
        let retVal = RegQueryValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0, &lpType, exePath, &exePathLength)
        if retVal <> ERROR_SUCCESS then
            raise (Win32Exception retVal)

        // Determine the number of characters without the terminating null.
        let exePath = 
            exePath.Substring(0, int exePathLength / 2 - 1)
            // Remove any environment strings.
            |> Environment.ExpandEnvironmentVariables

        let position = exePath.IndexOf '%'
        if position >= 0 then
            args <- exePath.Substring position
            // Remove command line parameters ('%0', etc.).
            exePath.Substring(0, position).Trim()
        else
            exePath

    member _.Extension =
        ext

    member _.Open
        with get () = openCmd
        and set (value) =
            if hAppIdHandle.IsInvalid || hAppIdHandle.IsClosed then
                raise (InvalidOperationException "Cannot write to registry key.")
            if not (File.Exists value) then
                raise (FileNotFoundException $"'{value}' does not exist")
            
            let cmd = value + " %1"
            let retVal = RegSetValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0, REG_SZ, value, value.Length + 1)
            if retVal <> ERROR_SUCCESS then
                raise (Win32Exception retVal)

    member this.Dispose() =
        this.Dispose true
        GC.SuppressFinalize this

    member _.Dispose(disposing) =
        // Ordinarily, we release unmanaged resources here
        // but all are wrapped by safe handles.

        // Release disposable objects.
        if disposing then
           if hExtHandle <> null then hExtHandle.Dispose()
           if hAppIdHandle <> null then hAppIdHandle.Dispose()

    interface IDisposable with
        member this.Dispose() =
            this.Dispose()
Imports Microsoft.Win32.SafeHandles
Imports System.ComponentModel
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text

Public Class FileAssociationInfo : Implements IDisposable
   ' Private variables.
   Private ext As String
   Private openCmd As String
   Private args As String
   Private hExtHandle, hAppIdHandle As SafeRegistryHandle

   ' Windows API calls.
   Private Declare Unicode Function RegOpenKeyEx Lib"advapi32.dll" _
                   Alias "RegOpenKeyExW" (hKey As IntPtr, lpSubKey As String, _
                   ulOptions As Integer, samDesired As Integer, _
                   ByRef phkResult As IntPtr) As Integer
   Private Declare Unicode Function RegQueryValueEx Lib "advapi32.dll" _
                   Alias "RegQueryValueExW" (hKey As IntPtr, _
                   lpValueName As String, lpReserved As Integer, _
                   ByRef lpType As UInteger, lpData As String, _
                   ByRef lpcbData As UInteger) As Integer
   Private Declare Function RegSetValueEx Lib "advapi32.dll" _
                  (hKey As IntPtr, _
                  <MarshalAs(UnmanagedType.LPStr)> lpValueName As String, _
                  reserved As Integer, dwType As UInteger, _
                  <MarshalAs(UnmanagedType.LPStr)> lpData As String, _
                  cpData As Integer) As Integer
   Private Declare Function RegCloseKey Lib "advapi32.dll" _
                  (hKey As IntPtr) As Integer

   ' Windows API constants.
   Private Const HKEY_CLASSES_ROOT As Integer = &h80000000
   Private Const ERROR_SUCCESS As Integer = 0

   Private Const KEY_QUERY_VALUE As Integer = 1
   Private Const KEY_SET_VALUE As Integer = &h2

   Private REG_SZ As UInteger = 1

   Private Const MAX_PATH As Integer  = 260

   Public Sub New(fileExtension As String)
      Dim retVal As Integer = 0
      Dim lpType As UInteger = 0

      If Not fileExtension.StartsWith(".") Then
         fileExtension = "." + fileExtension
      End If
      ext = fileExtension

      Dim hExtension As IntPtr = IntPtr.Zero
      ' Get the file extension value.
      retVal = RegOpenKeyEx(New IntPtr(HKEY_CLASSES_ROOT), fileExtension, 0,
                            KEY_QUERY_VALUE, hExtension)
      if retVal <> ERROR_SUCCESS Then
         Throw New Win32Exception(retVal)
      End If
      ' Instantiate the first SafeRegistryHandle.
      hExtHandle = New SafeRegistryHandle(hExtension, True)

      Dim appId As New String(" "c, MAX_PATH)
      Dim appIdLength As UInteger = CUInt(appId.Length)
      retVal = RegQueryValueEx(hExtHandle.DangerousGetHandle(), String.Empty, _
                               0, lpType, appId, appIdLength)
      if retVal <> ERROR_SUCCESS Then
         Throw New Win32Exception(retVal)
      End If
      ' We no longer need the hExtension handle.
      hExtHandle.Dispose()

      ' Determine the number of characters without the terminating null.
      appId = appId.Substring(0, CInt(appIdLength) \ 2 - 1) + "\shell\open\Command"

      ' Open the application identifier key.
      Dim exeName As New string(" "c, MAX_PATH)
      Dim exeNameLength As UInteger = CUInt(exeName.Length)
      Dim hAppId As IntPtr
      retVal = RegOpenKeyEx(New IntPtr(HKEY_CLASSES_ROOT), appId, 0,
                            KEY_QUERY_VALUE Or KEY_SET_VALUE, hAppId)
      If retVal <> ERROR_SUCCESS Then
         Throw New Win32Exception(retVal)
      End If

      ' Instantiate the second SafeRegistryHandle.
      hAppIdHandle = New SafeRegistryHandle(hAppId, True)

      ' Get the executable name for this file type.
      Dim exePath As New string(" "c, MAX_PATH)
      Dim exePathLength As UInteger = CUInt(exePath.Length)
      retVal = RegQueryValueEx(hAppIdHandle.DangerousGetHandle(), _
                               String.Empty, 0, lpType, exePath, exePathLength)
      If retVal <> ERROR_SUCCESS Then
         Throw New Win32Exception(retVal)
      End If
      ' Determine the number of characters without the terminating null.
      exePath = exePath.Substring(0, CInt(exePathLength) \ 2 - 1)

      exePath = Environment.ExpandEnvironmentVariables(exePath)
      Dim position As Integer = exePath.IndexOf("%"c)
      If position >= 0 Then
         args = exePath.Substring(position)
         ' Remove command line parameters ('%0', etc.).
         exePath = exePath.Substring(0, position).Trim()
      End If
      openCmd = exePath
   End Sub

   Public ReadOnly Property Extension As String
      Get
         Return ext
      End Get
   End Property

   Public Property Open As String
      Get
         Return openCmd
      End Get
      Set
        If hAppIdHandle.IsInvalid Or hAppIdHandle.IsClosed Then
           Throw New InvalidOperationException("Cannot write to registry key.")
        End If
        If Not File.Exists(value) Then
           Dim message As String = String.Format("'{0}' does not exist", value)
           Throw New FileNotFoundException(message)
        End If
        Dim cmd As String = value + " %1"
        Dim retVal As Integer = RegSetValueEx(hAppIdHandle.DangerousGetHandle(), String.Empty, 0,
                                              REG_SZ, value, value.Length + 1)
        If retVal <> ERROR_SUCCESS Then
           Throw New Win32Exception(retVal)
        End If
      End Set
   End Property

   Public Sub Dispose() _
      Implements IDisposable.Dispose
      Dispose(disposing:=True)
      GC.SuppressFinalize(Me)
   End Sub

   Protected Sub Dispose(disposing As Boolean)
      ' Ordinarily, we release unmanaged resources here
      ' but all are wrapped by safe handles.

      ' Release disposable objects.
      If disposing Then
         If hExtHandle IsNot Nothing Then hExtHandle.Dispose()
         If hAppIdHandle IsNot Nothing Then hAppIdHandle.Dispose()
      End If
   End Sub
End Class