System.GC.ReRegisterForFinalize 方法

方法描述

请求系统调用指定对象的终结器,此前已为该对象调用 SuppressFinalize。

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

public static void ReRegisterForFinalize(
	Object obj
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
obj System-Object 必须为其调用终结器的对象。
返回值 void

提示和注释

ReRegisterForFinalize 方法将 obj 参数添加到在垃圾回收器释放对象前会请求终止的对象列表中。 obj 参数必须是此方法的调用方。

调用 ReRegisterForFinalize 方法并不保证垃圾回收器将调用对象的终结器。

默认情况下,实现终结器的所有对象都会被添加到需要终止的对象列表中;但是,对象可能已经完成,或已通过调用 SuppressFinalize 方法禁用了终止。

终结器可以使用此方法使自己或引用的对象重新起用。

System.GC.ReRegisterForFinalize 方法例子

下面的示例演示如何使用 ReRegisterForFinalize 方法在垃圾回收后再次完成对象。

using System;

namespace ReRegisterForFinalizeExample
{
    class MyMainClass
    {
        static void Main()
        {
            // Create a MyFinalizeObject.
            MyFinalizeObject mfo = new MyFinalizeObject();

            // Release the reference to mfo.
            mfo = null;

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

            // At this point mfo will have gone through the first Finalize.
            // There should now be a reference to mfo in the static
            // MyFinalizeObject.currentInstance field.  Setting this value
            // to null and forcing another garbage collection will now
            // cause the object to Finalize permanently.
            MyFinalizeObject.currentInstance = null;
            GC.Collect();
        }
    }

    class MyFinalizeObject
    {
        public static MyFinalizeObject currentInstance = null;
        private bool hasFinalized = false;

        ~MyFinalizeObject()
        {
            if(hasFinalized == false)
            {
                Console.WriteLine("First finalization");

                // Put this object back into a root by creating
                // a reference to it.
                MyFinalizeObject.currentInstance = this;

                // Indicate that this instance has finalized once.
                hasFinalized = true;

                // Place a reference to this object back in the
                // finalization queue.
                GC.ReRegisterForFinalize(this);
            }
            else
            {
                Console.WriteLine("Second finalization");
            }
        }
    }
}

异常

异常 异常描述
ArgumentNullException obj 为 null。

命名空间

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 系统要求。