WeakReference WeakReference WeakReference WeakReference Class

定義

"弱い参照" を表します。弱い参照は、オブジェクトがガベージ コレクションによるクリアの対象になっている状態のままで、そのオブジェクトを参照します。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
継承
WeakReferenceWeakReferenceWeakReferenceWeakReference
属性
実装

次の例では、アプリケーションのリソースとしてオブジェクトのキャッシュを維持するために、弱い参照を使用する方法を示します。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. TargetプロパティをWeakReferenceオブジェクトは、データを表すバイト配列内のオブジェクト。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() WeakReference() WeakReference()
WeakReference(Object) WeakReference(Object) WeakReference(Object) WeakReference(Object)

指定したオブジェクトを参照する、WeakReference クラスの新しいインスタンスを初期化します。Initializes a new instance of the WeakReference class, referencing the specified object.

WeakReference(Object, Boolean) WeakReference(Object, Boolean) WeakReference(Object, Boolean) 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(SerializationInfo, StreamingContext) WeakReference(SerializationInfo, StreamingContext) WeakReference(SerializationInfo, StreamingContext)

指定したシリアル化およびストリーム オブジェクトからの逆シリアル化されたデータを使用して、WeakReference クラスの新しいインスタンスを初期化します。Initializes a new instance of the WeakReference class, using deserialized data from the specified serialization and stream objects.

プロパティ

IsAlive IsAlive IsAlive IsAlive

現在の WeakReference オブジェクトが参照するオブジェクトが、ガベージ コレクションで収集されているかどうかを示す値を取得します。Gets an indication whether the object referenced by the current WeakReference object has been garbage collected.

Target Target Target Target

現在の WeakReference オブジェクトが参照するオブジェクト (ターゲット) を取得または設定します。Gets or sets the object (the target) referenced by the current WeakReference object.

TrackResurrection TrackResurrection TrackResurrection TrackResurrection

現在の WeakReference オブジェクトが参照しているオブジェクトを、ファイナライズ後も追跡するかどうかを示す値を取得します。Gets an indication whether the object referenced by the current WeakReference object is tracked after it is finalized.

メソッド

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

指定したオブジェクトが、現在のオブジェクトと等しいかどうかを判断します。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()

現在の WeakReference オブジェクトが表すターゲットへの参照を破棄します。Discards the reference to the target represented by the current WeakReference object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

既定のハッシュ関数として機能します。Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

SerializationInfo オブジェクトに、現在の WeakReference オブジェクトをシリアル化するために必要なすべてのデータを格納します。Populates a SerializationInfo object with all the data needed to serialize the current WeakReference object.

GetType() GetType() GetType() GetType()

現在のインスタンスの Type を取得します。Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

現在の Object の簡易コピーを作成します。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

現在のオブジェクトを表す文字列を返します。Returns a string that represents the current object.

(Inherited from Object)

セキュリティ

SecurityPermission
アンマネージ コードを呼び出す機能。for the ability to call unmanaged code. 要求値: InheritanceDemand;アクセス許可の値。 UnmanagedCodeDemand value: InheritanceDemand; Permission value: UnmanagedCode

適用対象

こちらもご覧ください