英語で読む

次の方法で共有


GC.WaitForPendingFinalizers メソッド

定義

ファイナライザーのキューを処理するスレッドがそのキューを空にするまで、現在のスレッドを中断します。

C#
public static void WaitForPendingFinalizers ();

次の例では、メソッドを WaitForPendingFinalizers 使用して、収集されたすべてのオブジェクトの最終処理が完了するまで現在のスレッドを中断する方法を示します。

C#
using System;

namespace WaitForPendingFinalizersExample
{
   class MyWaitForPendingFinalizersClass
   {
    // You can increase this number to fill up more memory.
    const int numMfos = 1000;
    // You can increase this number to cause more
    // post-finalization work to be done.
    const int maxIterations = 100;

    static void Main(string[] args)
    {
       MyFinalizeObject mfo = null;

       // Create and release a large number of objects
       // that require finalization.
       for(int j = 0; j < numMfos; j++)
       {
          mfo = new MyFinalizeObject();
       }

       //Release the last object created in the loop.
       mfo = null;

       //Force garbage collection.
       GC.Collect();

       // Wait for all finalizers to complete before continuing.
       // Without this call to GC.WaitForPendingFinalizers,
       // the worker loop below might execute at the same time
       // as the finalizers.
       // With this call, the worker loop executes only after
       // all finalizers have been called.
       GC.WaitForPendingFinalizers();

       // Worker loop to perform post-finalization code.
       for(int i = 0; i < maxIterations; i++)
       {
          Console.WriteLine("Doing some post-finalize work");
       }
    }
   }

   class MyFinalizeObject
   {
    // Make this number very large to cause the finalizer to
    // do more work.
    private const int maxIterations = 10000;

    ~MyFinalizeObject()
    {
       Console.WriteLine("Finalizing a MyFinalizeObject");
            
       // Do some work.
       for(int i = 0; i < maxIterations; i++)
       {
          // This method performs no operation on i, but prevents
          // the JIT compiler from optimizing away the code inside
          // the loop.
          GC.KeepAlive(i);
       }
        }
    }
}

注釈

ガベージ コレクターは、再利用できるオブジェクトを見つけると、各オブジェクトをチェックして、オブジェクトの最終処理要件を決定します。 オブジェクトがファイナライザーを実装し、呼び出 SuppressFinalizeして終了処理を無効にしていない場合、オブジェクトは最終処理の準備完了としてマークされているオブジェクトの一覧に配置されます。 ガベージ コレクターは、 Finalize このリスト内のオブジェクトのメソッドを呼び出し、リストからエントリを削除します。 このメソッドは、すべてのファイナライザーが完了するまでブロックします。

ファイナライザーが実行されるスレッドは指定されていないため、このメソッドが終了する保証はありません。 ただし、このスレッドは、メソッドの進行中に別の WaitForPendingFinalizers スレッドによって中断される可能性があります。 たとえば、一定期間待機する別のスレッドを開始し、このスレッドがまだ中断されている場合は、このスレッドを中断できます。

適用対象

製品 バージョン
.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
.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
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0