Leggere in inglese

Condividi tramite


Object.Finalize Metodo

Definizione

Consente a un oggetto di effettuare un tentativo di liberare risorse ed eseguire altre operazioni di pulizia prima che venga recuperato da Garbage Collection.

C#
~Object();

Esempio

Nell'esempio seguente viene verificato che il Finalize metodo venga chiamato quando un oggetto che esegue l'override Finalize viene eliminato definitivamente. Si noti che, in un'applicazione di produzione, il Finalize metodo verrà sottoposto a override per rilasciare risorse non gestite mantenute dall'oggetto . Si noti anche che l'esempio C# fornisce un distruttore anziché eseguire l'override del Finalize metodo .

C#
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

Per un esempio aggiuntivo che esegue l'override del Finalize metodo , vedere il GC.SuppressFinalize metodo .

Commenti

Per altre informazioni su questa API, vedere Note sulle API supplementari per Object.Finalize.

Si applica a

Prodotto Versioni
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Vedi anche