WeakReference 類別

定義

表示弱式參考,即在參考物件的同時,仍允許系統透過記憶體回收來回收該物件。

public ref class WeakReference
public ref class WeakReference : System::Runtime::Serialization::ISerializable
public class WeakReference
public class WeakReference : System.Runtime.Serialization.ISerializable
[System.Serializable]
public class WeakReference : System.Runtime.Serialization.ISerializable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class WeakReference : System.Runtime.Serialization.ISerializable
type WeakReference = class
type WeakReference = class
    interface ISerializable
[<System.Serializable>]
type WeakReference = class
    interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type WeakReference = class
    interface ISerializable
Public Class WeakReference
Public Class WeakReference
Implements ISerializable
繼承
WeakReference
屬性
實作

範例

下列範例示範如何使用弱式參考來維護物件的快取作為應用程式的資源。 快取是使用 IDictionary<TKey,TValue> WeakReference 索引值索引鍵的物件來建構。 物件的 Target 屬性 WeakReference 是位元組陣列中代表資料的 物件。

此範例會隨機存取快取中的物件。 如果回收物件以進行垃圾收集,則會重新產生新的資料物件;否則,物件會因為弱式參考而可供存取。

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

// This class creates byte arrays to simulate data.
type Data(size) =
    let _data = Array.zeroCreate<byte> (size * 1024)
    
    // Simple property.
    member _.Name = 
        string size

type Cache(count) =
    // Dictionary to contain the cache.
    static let mutable _cache = Dictionary<int, WeakReference>()

    // Track the number of times an object is regenerated.
    let mutable regenCount = 0

    do
        _cache <- Dictionary<int, WeakReference>()
        // Add objects with a short weak reference to the cache.
        for i = 0 to count - 1 do
            _cache.Add(i, WeakReference(Data i, false))

    // Number of items in the cache.
    member _.Count =
        _cache.Count

    // Number of times an object needs to be regenerated.
    member _.RegenerationCount =
        regenCount

    // Retrieve a data object from the cache.
    member _.Item
        with get (index) =
            match _cache[index].Target with
            | :? Data as d->
                // Object was obtained with the weak reference.
                printfn $"Regenerate object at {index}: No"
                d
            | _ ->
                // If the object was reclaimed, generate a new one.
                printfn $"Regenerate object at {index}: Yes"
                let d = Data index
                _cache[index].Target <- d
                regenCount <- regenCount + 1
                d 

// Create the cache.
let cacheSize = 50
let r = Random()
let c = Cache cacheSize

let mutable dataName = ""
GC.Collect 0

// Randomly access objects in the cache.
for _ = 0 to c.Count - 1 do
    let index = r.Next c.Count

    // Access the object by getting a property value.
    dataName <- c[index].Name

// Show results.
let regenPercent = double c.RegenerationCount / double c.Count
printfn $"Cache size: {c.Count}, Regenerated: {regenPercent:P2}%%"

// 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%

備註

弱式參考可讓垃圾收集行程收集物件,同時仍允許應用程式存取物件。 如果您需要 物件,您仍然可以取得它的強式參考,並防止收集它。 如需如何使用簡短和長弱式參考的詳細資訊,請參閱 弱式參考

建構函式

WeakReference()
WeakReference(Object)

參考指定的物件,初始化 WeakReference 類別的新執行個體。

WeakReference(Object, Boolean)

參考指定的物件,並使用指定的重新恢復狀態追蹤,初始化 WeakReference 類別的新執行個體。

WeakReference(SerializationInfo, StreamingContext)

使用指定序列化和資料流物件的還原序列化資料,來初始化 WeakReference 類別的新執行個體。

屬性

IsAlive

取得目前 WeakReference 物件所參考的物件是否已進行記憶體回收的指示。

Target

取得或設定目前 WeakReference 物件所參考的物件 (目標)。

TrackResurrection

取得目前 WeakReference 物件所參考的物件是否要在結束後繼續追蹤的指示。

方法

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
Finalize()

捨棄對目前 WeakReference 物件所表示之目標的參考。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetObjectData(SerializationInfo, StreamingContext)

使用序列化目前 SerializationInfo 物件所需的所有資料,來填入 WeakReference 物件。

GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

適用於

另請參閱