Método System.Object.Finalize

En este artículo se proporcionan comentarios adicionales a la documentación de referencia de esta API.

El Finalize método se usa para realizar operaciones de limpieza en recursos no administrados mantenidos por el objeto actual antes de que se destruya el objeto. El método está protegido y, por tanto, solo es accesible a través de esta clase o a través de una clase derivada.

Funcionamiento de la finalización

La Object clase no proporciona ninguna implementación para el Finalize método y el recolector de elementos no utilizados no marca los tipos derivados de Object para la finalización a menos que invaliden el Finalize método .

Si un tipo invalida el Finalize método, el recolector de elementos no utilizados agrega una entrada para cada instancia del tipo a una estructura interna denominada cola de finalización. La cola de finalización contiene entradas para todos los objetos del montón administrado cuyo código de finalización debe ejecutarse antes de que el recolector de elementos no utilizados pueda reclamar su memoria. A continuación, el recolector de elementos no utilizados llama al Finalize método automáticamente en las condiciones siguientes:

  • Después de que el recolector de elementos no utilizados haya descubierto que un objeto no es accesible, a menos que el objeto se haya exento de la finalización mediante una llamada al GC.SuppressFinalize método .
  • Solo en .NET Framework, durante el apagado de un dominio de aplicación, a menos que el objeto esté exento de la finalización. Durante el apagado, se finalizan incluso los objetos a los que todavía se puede acceder.

Finalize solo se llama automáticamente una vez en una instancia determinada, a menos que el objeto se vuelva a registrar mediante un mecanismo como GC.ReRegisterForFinalize y el GC.SuppressFinalize método no se haya llamado posteriormente.

Finalize las operaciones tienen las siguientes limitaciones:

  • La hora exacta en que se ejecuta el finalizador no está definida. Para garantizar una versión determinista de los recursos para instancias de la clase, implemente un Close método o proporcione una IDisposable.Dispose implementación.
  • No se garantiza que los finalizadores de dos objetos se ejecuten en un orden específico, incluso si un objeto hace referencia al otro. Es decir, si el objeto A tiene una referencia al objeto B y ambos tienen finalizadores, es posible que el objeto B ya se haya finalizado cuando se inicie el finalizador del objeto A.
  • El subproceso en el que se ejecuta el finalizador no está especificado.

Es posible que el Finalize método no se ejecute hasta la finalización o que no se ejecute en absoluto en las siguientes circunstancias excepcionales:

  • Si otro finalizador se bloquea indefinidamente (entra en un bucle infinito, intenta obtener un bloqueo que nunca puede obtener, etc.). Dado que el tiempo de ejecución intenta ejecutar finalizadores hasta su finalización, es posible que no se llame a otros finalizadores si un finalizador se bloquea indefinidamente.
  • Si el proceso finaliza sin dar la oportunidad de limpiar el tiempo de ejecución. En este caso, la primera notificación del proceso del tiempo de ejecución es una notificación DLL_PROCESS_DETACH.

El tiempo de ejecución continúa finalizando los objetos durante el apagado solo mientras el número de objetos finalizables continúa disminuyendo.

Si Finalize o una invalidación de Finalize produce una excepción, y el tiempo de ejecución no está hospedado por una aplicación que invalida la directiva predeterminada, el tiempo de ejecución finaliza el proceso y no se ejecutan bloques o finalizadores activos/tryfinally. Este comportamiento garantiza la integridad del proceso si el finalizador no puede liberar ni destruir recursos.

Invalidación del método Finalize

Debe invalidar Finalize para una clase que use recursos no administrados, como identificadores de archivos o conexione de base de datos que se deben liberar cuando el objeto administrado que los usa se descarta durante la recolección de elementos no utilizados. No debe implementar un Finalize método para objetos administrados porque el recolector de elementos no utilizados libera automáticamente los recursos administrados.

Importante

Si hay un SafeHandle objeto disponible que encapsula el recurso no administrado, la alternativa recomendada es implementar el patrón dispose con un identificador seguro y no invalidar Finalize. Para obtener más información, consulte la sección alternativa Caja fuerte Handle.

El Object.Finalize método no hace nada de forma predeterminada, pero solo debe invalidar Finalize si es necesario y solo liberar recursos no administrados. La recuperación de memoria tiende a tardar mucho más si se ejecuta una operación de finalización, ya que requiere al menos dos recolecciones de elementos no utilizados. Además, debe invalidar el Finalize método solo para los tipos de referencia. Common Language Runtime solo finaliza los tipos de referencia. Omite los finalizadores en los tipos de valor.

El ámbito del Object.Finalize método es protected. Mantenga este ámbito limitado cuando reemplace el método en su clase. Al mantener protegido un Finalize método, se impide que los usuarios de la aplicación llamen directamente al método de Finalize un objeto.

Cada implementación de Finalize en un tipo derivado debe llamar a la implementación de su tipo base de Finalize. Este es el único caso en el que se permite que el código de aplicación llame Finalizea . El método de Finalize un objeto no debe llamar a un método en ningún objeto distinto del de su clase base. El motivo es que los otros objetos a los que se llama podrían ser recolectados al mismo tiempo que el objeto que llama, por ejemplo, en el caso de un cierre de Common Language Runtime.

Nota:

El compilador de C# no permite invalidar el Finalize método . En su lugar, se proporciona un finalizador mediante la implementación de un destructor para la clase . Un destructor de C# llama automáticamente al destructor de su clase base.

Visual C++ también proporciona su propia sintaxis para implementar el Finalize método . Para obtener más información, vea la sección "Destructores y finalizadores" de Cómo: Definir y consumir clases y estructuras (C++/CLI).

Dado que la recolección de elementos no utilizados no es determinista, no se sabe exactamente cuando el recolector de elementos no utilizados realiza la finalización. Para liberar recursos inmediatamente, también puede optar por implementar el patrón dispose y la IDisposable interfaz. Los IDisposable.Dispose consumidores de la clase pueden llamar a la implementación para liberar recursos no administrados y puede usar el Finalize método para liberar recursos no administrados en caso de que no se llame al Dispose método .

Finalize puede realizar casi cualquier acción, incluida la resurrección de un objeto (es decir, hacer que el objeto sea accesible de nuevo) después de que se haya limpiado durante la recolección de elementos no utilizados. Sin embargo, el objeto solo se puede resurrecr una vez; Finalize no se puede llamar a en objetos resurrecdos durante la recolección de elementos no utilizados.

La alternativa SafeHandle

La creación de finalizadores confiables suele ser difícil, ya que no puede realizar suposiciones sobre el estado de la aplicación y porque las excepciones del sistema no controladas, como OutOfMemoryException y StackOverflowException finalizan el finalizador. En lugar de implementar un finalizador para la clase para liberar recursos no administrados, puede usar un objeto derivado de la System.Runtime.InteropServices.SafeHandle clase para encapsular los recursos no administrados y, a continuación, implementar el patrón dispose sin un finalizador. .NET Framework proporciona las siguientes clases en el Microsoft.Win32 espacio de nombres que se derivan de System.Runtime.InteropServices.SafeHandle:

En el ejemplo siguiente se usa el patrón dispose con identificadores seguros en lugar de invalidar el Finalize método . Define una FileAssociation clase que encapsula la información del Registro sobre la aplicación que controla los archivos con una extensión de archivo determinada. Los dos identificadores del Registro devueltos como out parámetros por las llamadas de función RegOpenKeyEx de Windows se pasan al SafeRegistryHandle constructor. A continuación, el método protegido Dispose del tipo llama al SafeRegistryHandle.Dispose método para liberar estos dos identificadores.

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