WeakReference Classe

Definição

{1>Representa uma referência fraca, que faz referência a um objeto enquanto ainda permite que esse objeto seja recuperada pela coleta de lixo.<1}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
Herança
WeakReference
Atributos
Implementações

Exemplos

O exemplo a seguir demonstra como você pode usar referências fracas para manter um cache de objetos como um recurso para um aplicativo.The following example demonstrates how you can use weak references to maintain a cache of objects as a resource for an application. O cache é construído usando um IDictionary<TKey,TValue> de objetos WeakReference com chave por um valor de índice.The cache is constructed using an IDictionary<TKey,TValue> of WeakReference objects keyed by an index value. A propriedade Target para os objetos WeakReference é um objeto em uma matriz de bytes que representa dados.The Target property for the WeakReference objects is an object in a byte array that represents data.

O exemplo acessa aleatoriamente objetos no cache.The example randomly accesses objects in the cache. Se um objeto for recuperado para a coleta de lixo, um novo objeto de dados será regenerado; caso contrário, o objeto estará disponível para acesso devido à referência fraca.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% 

Comentários

Uma referência fraca permite que o coletor de lixo colete um objeto e, ao mesmo tempo, permita que um aplicativo acesse o objeto.A weak reference allows the garbage collector to collect an object while still allowing an application to access the object. Se você precisar do objeto, ainda poderá obter uma referência forte a ele e impedir que ele seja coletado.If you need the object, you can still obtain a strong reference to it and prevent it from being collected. Para obter mais informações sobre como usar referências fracas curtas e longas, consulte referências fracas.For more information about how to use short and long weak references, see Weak References.

Construtores

WeakReference()
WeakReference(Object)

Inicializa uma nova instância da classe WeakReference, fazendo referência ao objeto especificado.Initializes a new instance of the WeakReference class, referencing the specified object.

WeakReference(Object, Boolean)

Inicializa uma nova instância da classe WeakReference, fazendo referência ao objeto especificado e usando o acompanhamento de ressurreição especificado.Initializes a new instance of the WeakReference class, referencing the specified object and using the specified resurrection tracking.

WeakReference(SerializationInfo, StreamingContext)

Inicializa uma nova instância da classe WeakReference usando dados desserializados da serialização e dos objetos de fluxo especificados.Initializes a new instance of the WeakReference class, using deserialized data from the specified serialization and stream objects.

Propriedades

IsAlive

Obtém uma indicação se o objeto referenciado pelo objeto WeakReference atual passou pela coleta de lixo.Gets an indication whether the object referenced by the current WeakReference object has been garbage collected.

Target

Obtém ou define o objeto (o destino) referenciado pelo objeto WeakReference atual.Gets or sets the object (the target) referenced by the current WeakReference object.

TrackResurrection

Obtém uma indicação se o objeto referenciado pelo objeto WeakReference atual é acompanhado depois de finalizado.Gets an indication whether the object referenced by the current WeakReference object is tracked after it is finalized.

Métodos

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
Finalize()

Descarta a referência ao destino representado pelo objeto WeakReference atual.Discards the reference to the target represented by the current WeakReference object.

GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetObjectData(SerializationInfo, StreamingContext)

Popula um objeto SerializationInfo com todos os dados necessários para serializar o objeto WeakReference atual.Populates a SerializationInfo object with all the data needed to serialize the current WeakReference object.

GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)

Segurança

SecurityPermission
para a capacidade de chamar código não gerenciado.for the ability to call unmanaged code. Valor de demanda: InheritanceDemand; Valor da permissão: UnmanagedCodeDemand value: InheritanceDemand; Permission value: UnmanagedCode

Aplica-se a

Veja também