WeakReference 类

定义

表示弱引用,即在引用对象的同时仍然允许垃圾回收来回收该对象。Represents a weak reference, which references an object while still allowing that object to be reclaimed by garbage collection.

public ref class WeakReference : System::Runtime::Serialization::ISerializable
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class WeakReference : System.Runtime.Serialization.ISerializable
type WeakReference = class
    interface ISerializable
Public Class WeakReference
Implements ISerializable
继承
WeakReference
属性
实现

示例

下面的示例演示如何使用弱引用将对象缓存维护为应用程序的资源。The following example demonstrates how you can use weak references to maintain a cache of objects as a resource for an application. 缓存是使用IDictionary<TKey,TValue>由索引值进行WeakReference键控的对象的构造的。The cache is constructed using an IDictionary<TKey,TValue> of WeakReference objects keyed by an index value. WeakReference对象Target的属性是表示数据的字节数组中的对象。The Target property for the WeakReference objects is an object in a byte array that represents data.

该示例将随机访问缓存中的对象。The example randomly accesses objects in the cache. 如果回收对象进行垃圾回收, 则会重新生成新的数据对象;否则, 可以访问该对象, 因为存在弱引用。If an object is reclaimed for garbage collection, a new data object is regenerated; otherwise, the object is available to access because of the weak reference.

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 = "";
        GC.Collect(0);
        
        // 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/(double)c.Count;
        Console.WriteLine("Cache size: {0}, Regenerated: {1:P2}%", c.Count, regenPercent);
    }
}

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

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

    // Number of times an object needs to be regenerated.
    public int RegenerationCount
    {
        get { return regenCount; }
    }

    // Retrieve a data object from the cache.
    public Data this[int index]
    {
        get {
            Data d = _cache[index].Target as Data;
            if (d == null) {
                // If the object was reclaimed, generate a new one.
                Console.WriteLine("Regenerate object at {0}: Yes", index);
                d = new Data(index);
                _cache[index].Target = d;
                regenCount++;
            }
            else {
                // Object was obtained with the weak reference.
                Console.WriteLine("Regenerate object at {0}: No", index);
            }

            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%
Imports System.Collections.Generic

Public Class Example
    Public Shared Sub Main()
        ' Create the cache. 
        Dim cacheSize As Integer = 50
        Dim r As Random = New Random()
        Dim c As Cache = New Cache(cacheSize)

        Dim DataName As String = "" 
        GC.Collect(0)
        
        ' Randomly access objects in the cache. 
        For ctr As Integer = 0 To C.Count - 1 
            Dim index As Integer = r.Next(c.Count)

            ' Access the object by getting a property value.
            DataName = c(index).Name
        Next 

        ' Show results. 
        Dim regenPercent As Double = c.RegenerationCount * 100 / c.Count
        Console.WriteLine("Cache size: {0}, Regenerated: {1}%", c.Count, regenPercent)
    End Sub 
End Class 

Public Class Cache
    ' Dictionary to contain the cache. 
    Private Shared _cache As Dictionary(Of Integer, WeakReference)

    ' Track the number of times an object is regenerated. 
    Dim regenCount As Integer = 0

    Public Sub New(ByVal count As Integer)
        _cache = New Dictionary(Of Integer, WeakReference)

        ' Add data objects with a short weak reference to the cache. 
        For ctr = 0 To count - 1
            _cache.Add(ctr, New WeakReference(New Data(ctr)))
        Next
    End Sub 

    ' Number of items in the cache. 
    Public ReadOnly Property Count() As Integer 
        Get 
            Return _cache.Count
        End Get 
    End Property 

    ' Number of times an object needs to be regenerated. 
    Public ReadOnly Property RegenerationCount() As Integer 
        Get 
            Return regenCount
        End Get 
    End Property 

    ' Retrieve a data object from the cache. 
    Default Public ReadOnly Property Item(ByVal index As Integer) As Data
        Get 
            Dim d As Data = TryCast(_cache(index).Target, Data)
            ' If the object was reclaimed, generate a new one.
            If d Is Nothing Then 
                Console.WriteLine("Regenerate object at {0}: Yes", index)
                d = New Data(index)
                _cache(index).Target = d
                regenCount += 1
           Else 
                ' Object was obtained with the weak reference.
                Console.WriteLine("Regenerate object at {0}: No", index.ToString())
            End If 
            Return d
        End Get 
    End Property 
End Class 

' Class that creates byte arrays to simulate data. 
Public Class Data
    Private _data() As Byte 
    Private _name As String 

    Public Sub New(ByVal size As Integer)
        _data = New Byte(((size * 1024)) - 1) {}
        _name = size.ToString
    End Sub 

    ' Simple property for accessing the object. 
    Public ReadOnly Property Name() As String 
        Get 
            Return _name
        End Get 
    End Property 
End Class 
' 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% 

注解

弱引用允许垃圾回收器收集对象, 同时仍允许应用程序访问对象。A weak reference allows the garbage collector to collect an object while still allowing an application to access the object. 如果需要对象, 则仍可获得对它的强引用, 并阻止收集该对象。If you need the object, you can still obtain a strong reference to it and prevent it from being collected. 有关如何使用短弱引用和长弱引用的详细信息, 请参阅弱引用For more information about how to use short and long weak references, see Weak References.

构造函数

WeakReference()
WeakReference(Object)

引用指定的对象初始化 WeakReference 类的新实例。Initializes a new instance of the WeakReference class, referencing the specified object.

WeakReference(Object, Boolean)

初始化 WeakReference 类的新实例,引用指定的对象并使用指定的复活跟踪。Initializes a new instance of the WeakReference class, referencing the specified object and using the specified resurrection tracking.

WeakReference(SerializationInfo, StreamingContext)

使用从指定的序列化和流对象反序列化的数据,初始化 WeakReference 类的新实例。Initializes a new instance of the WeakReference class, using deserialized data from the specified serialization and stream objects.

属性

IsAlive

获取当前 WeakReference 对象引用的对象是否已被垃圾回收的指示。Gets an indication whether the object referenced by the current WeakReference object has been garbage collected.

Target

获取或设置当前 WeakReference 对象引用的对象(目标)。Gets or sets the object (the target) referenced by the current WeakReference object.

TrackResurrection

获取当前 WeakReference 对象引用的对象在终止后是否会被跟踪的指示。Gets an indication whether the object referenced by the current WeakReference object is tracked after it is finalized.

方法

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
Finalize()

丢弃对当前 WeakReference 对象表示的目标的引用。Discards the reference to the target represented by the current WeakReference object.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetObjectData(SerializationInfo, StreamingContext)

使用序列化当前的 SerializationInfo 对象所需的所有数据填充 WeakReference 对象。Populates a SerializationInfo object with all the data needed to serialize the current WeakReference object.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)

安全性

SecurityPermission
用于调用非托管代码。for the ability to call unmanaged code. 要求值: InheritanceDemand;权限值:UnmanagedCodeDemand value: InheritanceDemand; Permission value: UnmanagedCode

适用于

另请参阅