本文档已存档,并且将不进行维护。

WeakReference 类

表示弱引用,即在引用对象的同时仍然允许垃圾回收来回收该对象。

命名空间: System
程序集: mscorlib(在 mscorlib.dll 中)

[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public class WeakReference : ISerializable
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public class WeakReference implements ISerializable
SerializableAttribute 
ComVisibleAttribute(true) 
public class WeakReference implements ISerializable
不适用。

弱引用允许垃圾回收器在回收对象的同时仍然允许应用程序访问该对象。如果需要该对象,则仍然可以获取对该对象的强引用,并阻止对它进行回收。有关如何使用短弱引用和长弱引用的更多信息,请参见使用弱引用

下面的代码示例创建 ClassA 类的一个实例以跟踪弱引用。不等待发生垃圾回收,Timer 用于引起垃圾回收或将弱引用更改回对该对象的强引用。将 WeakReference 构造函数从 false 更改为 true 来检查短弱引用和长弱引用中的输出结果。

using System;
using System.Timers;

class Program
{

    static void Main(string[] args)
    {

        // Creating an instance
        // of an object creates
        // a strong reference.
        ClassA objA1 = new ClassA();

        // Create a short weak reference to the object.
        // Specify true for a long weak reference.
        WeakReference wr = new WeakReference(objA1, false);

        // Set the target of the
        // weak reference to the object.
        wr.Target = objA1;

        // Remove the strong reference
        // the application has to the object.
        objA1 = null;
        if (objA1 == null)
        {
            Console.WriteLine("After setting objA1 to null: objA1 is null.");
        }

        // Set a timer to set a strong reference
        // and to force garbage collection.
        System.Timers.Timer aTimer = new System.Timers.Timer();

        // Set interval to 5 seconds.
        aTimer.Interval = 5000;
        aTimer.Enabled = true;

        // Counter for tracking.
        int count = 1;

        // Anonymous method.
        aTimer.Elapsed += delegate(object sender,
            System.Timers.ElapsedEventArgs e)
        {
            if (objA1 == null)
            {
                Console.WriteLine("objA1 is null");

                // Adjust the count higher if
                // you want to allow more time
                // for automatic garbage collection.
                if (count == 5)
                {
                    // Uncomment next line to set a strong reference.
                    //objA1 = (ClassA)wr.Target;
                    GC.Collect();
                }

                if (count == 8)
                {
                    // This code is only reached if
                    // the weak reference is long.
                    objA1 = (ClassA)wr.Target;

                }
                if (wr.IsAlive == false)
                {
                    // Object is collected and
                    // all references terminated.
                    Console.WriteLine("Object collected");
                    aTimer.Stop();
                }
                else
                {
                    Console.WriteLine("count {0}, still alive. long weak reference: {1}",
                        count.ToString(),
                        wr.TrackResurrection.ToString());
                    count++;
                }
            }
            else
            {
                // A strong reference is established
                // and prevents it being collected.
                Console.WriteLine("Strong reference applied");
                aTimer.Stop();
            }
        };
    }

}
public class ClassA
{
    public ClassA()
    {

    }

    ~ClassA()
    {
        Console.WriteLine("Finalized.");
    }

    void MakeSomeGarbage()
    {
        // Create objects and release them
        // to fill up memory with unused objects.
        Version vt;

        for (int i = 0; i < 10000; i++)
        {
            vt = new Version();
        }
    }
}


// -------- Code example output --------
//
// A short weak reference creates
// the following output:
// ------------------------------------
// After setting objA1 to null: objA1 is null.
// objA1 is null
// count 1, still alive. long weak reference: False
// objA1 is null
// count 2, still alive. long weak reference: False
// objA1 is null
// count 3, still alive. long weak reference: False
// objA1 is null
// count 4, still alive. long weak reference: False
// objA1 is null
// Object collected
// Finalized.
// ------------------------------------
//
//
// A long weak reference creates
// the following output, being
// ressurected at count 5.
// ------------------------------------
// After setting objA1 to null: objA1 is null.
// objA1 is null
// count 1, still alive. long weak reference: True
// objA1 is null
// count 2, still alive. long weak reference: True
// objA1 is null
// count 3, still alive. long weak reference: True
// objA1 is null
// count 4, still alive. long weak reference: True
// objA1 is null
// count 5, still alive. long weak reference: True
// Finalized.
// objA1 is null
// count 6, still alive. long weak reference: True
// objA1 is null
// count 7, still alive. long weak reference: True
// objA1 is null
// count 8, still alive. long weak reference: True
// Strong reference applied
// ----------------------------------
//
//
// A weak reference creates
// the following output with a
// strong reference applied
// at count 5.
// ----------------------------------
// After setting objA1 to null: objA1 is null.
// objA1 is null
// count 1, still alive. long weak reference: False
// objA1 is null
// count 2, still alive. long weak reference: False
// objA1 is null
// count 3, still alive. long weak reference: False
// objA1 is null
// count 4, still alive. long weak reference: False
// objA1 is null
// count 5, still alive. long weak reference: False
// Strong reference applied
// ------------------------------------
//

System.Object
  System.WeakReference

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

Windows Vista、Microsoft Windows XP SP2 和 Windows Server 2003 SP1 支持 Microsoft .NET Framework 3.0。

.NET Framework

受以下版本支持:3.0、2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

XNA Framework

受以下版本支持:1.0
显示: