System.GC.WaitForPendingFinalizers 方法

方法描述

挂起当前线程,直到处理终结器队列的线程清空该队列为止。

语法定义(C# System.GC.WaitForPendingFinalizers 方法 的用法)

public static void WaitForPendingFinalizers()

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
返回值 void

提示和注释

当垃圾回收器找到可以回收的对象时,它会检查每个对象以确定对象的终止要求。 如果对象实现终结器,并且尚未通过调用 SuppressFinalize 禁用终止,则会将该对象置于标记为准备终止的对象的列表中。 垃圾回收器将为此列表中的对象调用 Finalize 方法,并从该列表中移除这些项。 此方法将一直阻止,直到所有终结器均运行结束为止。

未指定运行终结器的线程,因此不能保证此方法将会终止。 然而,在 WaitForPendingFinalizers 方法正在执行时,此线程可以由另一个线程中断。 例如,可以启动另一个线程,该线程在等待一段时间后,如果此线程仍然挂起,则中断此线程。

System.GC.WaitForPendingFinalizers 方法例子

下面的示例演示如何使用 WaitForPendingFinalizers 方法挂起当前线程,直到所有回收的对象终止。

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);
	   }
        }
    }
}

异常

异常 异常描述

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。