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

WeakReference 类

更新:2007 年 11 月

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

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

[SerializableAttribute]
[ComVisibleAttribute(true)]
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public class WeakReference : ISerializable
/** @attribute SerializableAttribute */ 
/** @attribute ComVisibleAttribute(true) */
/** @attribute SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode) */
public class WeakReference implements ISerializable
public class WeakReference implements ISerializable

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

下面的代码示例演示如何使用弱引用将对象的缓存作为应用程序的资源进行维护。此缓存是使用以索引值为关键字的 WeakReference 对象的 IDictionary<TKey, TValue> 构建的。WeakReference 对象的 Target 属性是一个表示数据的字节数组中的对象。

此示例将随机访问缓存中的对象。如果通过垃圾回收来回收对象,则将重新生成新的数据对象;否则,该对象会因弱引用而可访问。

using System;
using System.Collections.Generic;

public class Program
{

    public static void Main()
    {

        // Create the cache.
        int cacheSize = 50;
        Random r = new Random();
        Cache c = new Cache(cacheSize);

        string DataName = "";

        // Randomly access objects in the cache.
        for (int i = 0; i < c.Count; i++)
        {
            int index = r.Next(c.Count);

            // Access the object by
            // getting a property value.
            DataName = c[index].Name;
        }
        // Show results.
        double regenPercent = c.RegenerationCount * 100 / c.Count;
        Console.WriteLine("Cache size: {0}, Regenerated: {1}%", c.Count.ToString(), regenPercent.ToString());

    }
}


public class Cache
{
    // Dictionary to contain the cache.
    static Dictionary<int, WeakReference> _cache;

    // Track the number of times an 
    // object is regenerated.
    int regenCount = 0;   

    public Cache(int count)
    {

        _cache = new Dictionary<int, WeakReference>();

        // Add data objects with a 
        // short weak reference to the cache.
       for (int i = 0; i < count; i++)
        {
            _cache.Add(i, new WeakReference(new Data(i), false));
        }

    }

    // Returns the number of items in the cache.
    public int Count
    {
        get
        {
            return _cache.Count;
        }
    }

    // Returns the number of times an 
    // object had to be regenerated.
    public int RegenerationCount
    {
        get
        {
            return regenCount;
        }
    }

    // Accesses a data object from the cache.
    // If the object was reclaimed for garbage collection,
    // create a new data object at that index location.
    public Data this[int index]
    {
        get
        {
            // Obtain an instance of a data
            // object from the cache of
            // of weak reference objects.
            Data d = _cache[index].Target as Data;
            if (d == null)
            {
                // Object was reclaimed, so generate a new one.
                Console.WriteLine("Regenerate object at {0}: Yes", index.ToString());
                d = new Data(index);
                regenCount++;
            }
            else
            {
                // Object was obtained with the weak reference.
                Console.WriteLine("Regenerate object at {0}: No", index.ToString());
            }

            return d;
       }

    }

}


// This class creates byte arrays to simulate data.
public class Data
{
    private byte[] _data;
    private string _name;

    public Data(int size)
    {
        _data = new byte[size * 1024];
        _name = size.ToString();
    }

    // Simple property.
    public string Name
    {
        get
        {
            return _name;
        }
    }

}

// Example of the last lines of the output:
//
// ...
// Regenerate object at 36: Yes
// Regenerate object at 8: Yes
// Regenerate object at 21: Yes
// Regenerate object at 4: Yes
// Regenerate object at 38: No
// Regenerate object at 7: Yes
// Regenerate object at 2: Yes
// Regenerate object at 43: Yes
// Regenerate object at 38: No
// Cache size: 50, Regenerated: 94%
//


System.Object
  System.WeakReference

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

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

.NET Framework 和 .NET Compact Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求

.NET Framework

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

.NET Compact Framework

受以下版本支持:3.5、2.0、1.0

XNA Framework

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