.NET Framework Class Library Object..::.Finalize Method Updated: December 2010 Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
Namespace:
System
Assembly:
mscorlib (in mscorlib.dll)

Syntax
Protected Overridable Sub Finalize
protected virtual void Finalize()
protected:
virtual void Finalize()
abstract Finalize : unit -> unit
override Finalize : unit -> unit

Remarks
The Finalize method is used to perform cleanup operations on unmanaged resources held by the current object before the current object is destroyed. The method is protected and therefore is accessible only through this class or through a derived class. This method is automatically called after an object becomes inaccessible, unless the object has been exempted from finalization by a call to GC..::.SuppressFinalize. During shutdown of an application domain, Finalize is automatically called on objects that are not exempt from finalization, even those that are still accessible. Finalize is automatically called only once on a given instance, unless the object is re-registered using a mechanism such as GC..::.ReRegisterForFinalize and GC..::.SuppressFinalize has not been subsequently called. Every implementation of Finalize in a derived type must call its base type's implementation of Finalize. This is the only case in which application code is allowed to call Finalize. Note |
|---|
Because the C# compiler does not allow you to directly implement the Finalize method, a C# destructor automatically calls the destructor of its base class. |
Finalize operations have the following limitations: The exact time when the finalizer executes during garbage collection is undefined. Resources are not guaranteed to be released at any specific time, unless calling a Close method or a Dispose method. The finalizers of two objects are not guaranteed to run in any specific order, even if one object refers to the other. That is, if Object A has a reference to Object B and both have finalizers, Object B might have already finalized when the finalizer of Object A starts. The thread on which the finalizer is run is unspecified.
The Finalize method might not run to completion or might not run at all in the following exceptional circumstances: Another finalizer blocks indefinitely (goes into an infinite loop, tries to obtain a lock it can never obtain and so on). Because the runtime attempts to run finalizers to completion, other finalizers might not be called if a finalizer blocks indefinitely. The process terminates without giving the runtime a chance to clean up. In this case, the runtime's first notification of process termination is a DLL_PROCESS_DETACH notification.
The runtime continues to Finalize objects during shutdown only while the number of finalizable objects continues to decrease. If Finalize or an override of Finalize throws an exception, and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process and no active try-finally blocks or finalizers are executed. This behavior ensures process integrity if the finalizer cannot free or destroy resources. Notes to Implementers
Object..::.Finalize does nothing by default. It must be overridden by a derived class only if necessary, because reclamation during garbage collection tends to take much longer if a Finalize operation must be run. If an Object holds references to any resources, Finalize must be overridden by a derived class in order to free these resources before the Object is discarded during garbage collection. A type must implement Finalize when it uses unmanaged resources such as file handles or database connections that must be released when the managed object that uses them is reclaimed. See the IDisposable interface for a complementary and more controllable means of disposing resources.
Finalize can take any action, including resurrecting an object (that is, making the object accessible again) after it has been cleaned up during garbage collection. However, the object can only be resurrected once; Finalize cannot be called on resurrected objects during garbage collection. Destructors are the C# mechanism for performing cleanup operations. Destructors provide appropriate safeguards, such as automatically calling the base type's destructor. In C# code, Object..::.Finalize cannot be called or overridden.

Examples
The following example verifies that the Finalize method is called when an object that overrides Finalize is destroyed. Note that, in a production application, the Finalize method would be overridden to release unmanaged resources held by the object. Also note that the C# example provides a destructor instead of overriding the Finalize method.
Imports System.Diagnostics
Public Class ExampleClass
Dim sw As StopWatch
Public Sub New()
sw = Stopwatch.StartNew()
Console.WriteLine("Instantiated object")
End Sub
Public Sub ShowDuration()
Console.WriteLine("This instance of {0} has been in existence for {1}",
Me, sw.Elapsed)
End Sub
Protected Overrides Sub Finalize()
Console.WriteLine("Finalizing object")
sw.Stop()
Console.WriteLine("This instance of {0} has been in existence for {1}",
Me, sw.Elapsed)
End Sub
End Class
Module Demo
Public Sub Main()
Dim ex As New ExampleClass()
ex.ShowDuration()
End Sub
End Module
' The example displays output like the following:
' Instantiated object
' This instance of ExampleClass has been in existence for 00:00:00.0011060
' Finalizing object
' This instance of ExampleClass has been in existence for 00:00:00.0036294
using System;
using System.Diagnostics;
public class ExampleClass
{
Stopwatch sw;
public ExampleClass()
{
sw = Stopwatch.StartNew();
Console.WriteLine("Instantiated object");
}
public void ShowDuration()
{
Console.WriteLine("This instance of {0} has been in existence for {1}",
this, sw.Elapsed);
}
~ExampleClass()
{
Console.WriteLine("Finalizing object");
sw.Stop();
Console.WriteLine("This instance of {0} has been in existence for {1}",
this, sw.Elapsed);
}
}
public class Demo
{
public static void Main()
{
ExampleClass ex = new ExampleClass();
ex.ShowDuration();
}
}
// The example displays output like the following:
// Instantiated object
// This instance of ExampleClass has been in existence for 00:00:00.0011060
// Finalizing object
// This instance of ExampleClass has been in existence for 00:00:00.0036294

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileSupported in: 4, 3.5 SP1 Portable Class LibrarySupported in: Portable Class Library

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

See Also

Change History
Date | History | Reason |
|---|
December 2010
| Noted that C# destructors call the base class Finalize method, and added an example. |
Customer feedback.
|
|
Biblioteca de clases de .NET Framework Object..::.Finalize (Método) Permite que un objeto intente liberar recursos y realizar otras operaciones de limpieza antes de ser reclamado por la recolección de elementos no utilizados.
Espacio de nombres:
System
Ensamblado:
mscorlib (en mscorlib.dll)

Sintaxis
Protected Overridable Sub Finalize
protected virtual void Finalize()
protected:
virtual void Finalize()
abstract Finalize : unit -> unit
override Finalize : unit -> unit

Comentarios
El método Finalize se utiliza para realizar operaciones de la limpieza en recursos no administrados mantenidos por el objeto actual antes de que se destruya el objeto actual. El método está protegido y, por lo tanto, solo se puede obtener acceso a él a través de esta clase o de una clase derivada. Este método se invoca de forma automática, después de que un objeto pase a ser inaccesible, salvo que haya sido excluido del proceso de finalización mediante una llamada a GC..::.SuppressFinalize. Durante el apagado de un dominio de aplicación, se llama a Finalize automáticamente en los objetos que no están exentos de la finalización, incluso aquéllos que todavía son accesibles. Finalize se llama automáticamente sólo una vez en una instancia determinada, a menos que el objeto se registre de nuevo mediante un mecanismo como GC..::.ReRegisterForFinalize y como consecuencia no se ha llamado a GC..::.SuppressFinalize. Todas las implementaciones de Finalize en un tipo derivado deben llamar a la correspondiente implementación de tipo base de Finalize. Este es el único caso en el que se permite al código de la aplicación llamar a Finalize. Nota |
|---|
Dado que el compilador de C# no permite implementar el método Finalize directamente, un destructor de C# llama automáticamente al destructor de su clase base. |
Las operaciones de Finalize tienen las siguientes limitaciones: El momento exacto en que se ejecuta el finalizador durante la recolección de elementos no utilizados no está definido. No se garantiza la liberación de recursos en un momento concreto, a menos que se llame a un método Close o a un método Dispose. No se garantiza que los finalizadores de dos objetos se ejecuten en un orden determinado, aunque un objeto haga referencia al otro. Es decir, si el objeto A hace referencia al objeto B y ambos tienen finalizadores, puede que el objeto B ya haya terminado cuando se inicie el finalizador del objeto A. No se ha especificado el subproceso en el que se ejecuta el finalizador.
Puede que el método Finalize no se ejecute hasta su finalización o puede que no llegue a ejecutarse en las siguientes circunstancias excepcionales: Otro finalizador se ha bloqueado de forma indefinida (entra en un bucle infinito, intenta obtener un bloqueo que nunca puede conseguir, etc.). Como el motor en tiempo de ejecución intenta ejecutar los finalizadores hasta su terminación, puede que no se llame a otros finalizadores si un finalizador se bloquea de forma indefinida. El proceso termina sin que el motor en tiempo de ejecución pueda efectuar una limpieza. En este caso, la primera notificación de terminación del proceso por parte del motor en tiempo de ejecución es una notificación DLL_PROCESS_DETACH.
El motor en tiempo de ejecución sigue hasta los objetos Finalize durante el cierre sólo si el número de objetos susceptibles de finalización sigue reduciéndose. Si Finalize o un reemplazo de Finalize produce una excepción y el motor en tiempo de ejecución no está hospedado por una aplicación que reemplace la directiva predeterminada, dicho motor finalizará el proceso y no se ejecutarán finalizadores ni bloques try-finally activos. Este comportamiento garantiza la integridad del proceso si el finalizador no puede liberar ni destruir recursos. Notas para los implementadores
Object..::.Finalize no realiza ninguna acción de forma predeterminada. Debe ser reemplazado por una clase derivada sólo si es necesario, porque la reclamación durante la recolección de elementos no utilizados suele tardar mucho más tiempo si debe ejecutarse una operación de Finalize. Si un objeto Object contiene referencias a recursos, Finalize debe ser reemplazado por una clase derivada para que estos recursos se liberen antes de que Object se descarte durante la recolección de elementos no utilizados. Un tipo debe implementar Finalize cuando utiliza recursos no administrados, como identificadores de archivo o conexiones de base de datos que deben liberarse cuando se reclama el objeto administrado que los utiliza. Vea la interfaz IDisposable para obtener información sobre un medio complementario y más controlable de eliminar recursos.
Finalize puede llevar a cabo cualquier acción, como el restablecimiento de un objeto (es decir, hacer que el objeto vuelva a ser accesible) después de su limpieza durante la recolección de elementos no utilizados. Sin embargo, el objeto sólo puede restablecerse una vez; no se puede llamar a Finalize en objetos restablecidos durante la recolección de elementos no utilizados. Los destructores son el mecanismo de C# para realizar operaciones de limpieza. Proporcionan mecanismos de protección apropiados, como la llamada automática al destructor de tipo base. En el caso del código de C#, no se puede llamar al método Object..::.Finalize ni reemplazarlo.

Ejemplos
El siguiente ejemplo comprueba que se llama al método Finalize cuando se destruye un objeto que invalida Finalize. Tenga en cuenta que, en una aplicación de producción, el método Finalize se invalidaría para liberar recursos no administrados retenidos por el objeto. También observe que el ejemplo de C# proporciona un destructor en lugar de invalidar el método Finalize.
Imports System.Diagnostics
Public Class ExampleClass
Dim sw As StopWatch
Public Sub New()
sw = Stopwatch.StartNew()
Console.WriteLine("Instantiated object")
End Sub
Public Sub ShowDuration()
Console.WriteLine("This instance of {0} has been in existence for {1}",
Me, sw.Elapsed)
End Sub
Protected Overrides Sub Finalize()
Console.WriteLine("Finalizing object")
sw.Stop()
Console.WriteLine("This instance of {0} has been in existence for {1}",
Me, sw.Elapsed)
End Sub
End Class
Module Demo
Public Sub Main()
Dim ex As New ExampleClass()
ex.ShowDuration()
End Sub
End Module
' The example displays output like the following:
' Instantiated object
' This instance of ExampleClass has been in existence for 00:00:00.0011060
' Finalizing object
' This instance of ExampleClass has been in existence for 00:00:00.0036294
using System;
using System.Diagnostics;
public class ExampleClass
{
Stopwatch sw;
public ExampleClass()
{
sw = Stopwatch.StartNew();
Console.WriteLine("Instantiated object");
}
public void ShowDuration()
{
Console.WriteLine("This instance of {0} has been in existence for {1}",
this, sw.Elapsed);
}
~ExampleClass()
{
Console.WriteLine("Finalizing object");
sw.Stop();
Console.WriteLine("This instance of {0} has been in existence for {1}",
this, sw.Elapsed);
}
}
public class Demo
{
public static void Main()
{
ExampleClass ex = new ExampleClass();
ex.ShowDuration();
}
}
// The example displays output like the following:
// Instantiated object
// This instance of ExampleClass has been in existence for 00:00:00.0011060
// Finalizing object
// This instance of ExampleClass has been in existence for 00:00:00.0036294

Información de versión
.NET FrameworkCompatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileCompatible con: 4, 3.5 SP1 Compatible con:

Plataformas
Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2
.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Vea también

Historial de cambios
Fecha | Historial | Motivo |
|---|
Diciembre de 2010
| Indicado que los destructores de C# llaman al método de clase base Finalize, y agregado un ejemplo. |
Comentarios de los clientes.
|
|