Ler em inglês

Compartilhar via


WeakReference Classe

Definição

Representa uma referência fraca, que faz referência a um objeto enquanto ainda permite que esse objeto seja recuperada pela coleta de lixo.

C#
public class WeakReference
C#
public class WeakReference : System.Runtime.Serialization.ISerializable
C#
[System.Serializable]
public class WeakReference : System.Runtime.Serialization.ISerializable
C#
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class WeakReference : System.Runtime.Serialization.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. O cache é construído usando um IDictionary<TKey,TValue> dos WeakReference objetos chaveados por um valor de índice. A Target propriedade para os WeakReference objetos é um objeto em uma matriz de bytes que representa dados.

O exemplo acessa aleatoriamente objetos no cache. Se um objeto for recuperado para coleta de lixo, um novo objeto de dados será regenerado; caso contrário, o objeto está disponível para acesso devido à referência fraca.

C#
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%

Comentários

Uma referência fraca permite que o coletor de lixo colete um objeto enquanto ainda permite que um aplicativo acesse o objeto. Se você precisar do objeto, ainda poderá obter uma referência forte a ele e impedir que ele seja coletado. Para obter mais informações sobre como usar referências fracas curtas e longas, consulte Referências Fracas.

Construtores

WeakReference()
WeakReference(Object)

Inicializa uma nova instância da classe WeakReference, fazendo referência ao objeto especificado.

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.

WeakReference(SerializationInfo, StreamingContext)

Inicializa uma nova instância da classe WeakReference usando dados desserializados da serialização e dos objetos de fluxo especificados.

Propriedades

IsAlive

Obtém uma indicação se o objeto referenciado pelo objeto WeakReference atual passou pela coleta de lixo.

Target

Obtém ou define o objeto (o destino) referenciado pelo objeto WeakReference atual.

TrackResurrection

Obtém uma indicação se o objeto referenciado pelo objeto WeakReference atual é acompanhado depois de finalizado.

Métodos

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
Finalize()

Descarta a referência ao destino representado pelo objeto WeakReference atual.

GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetObjectData(SerializationInfo, StreamingContext)

Popula um objeto SerializationInfo com todos os dados necessários para serializar o objeto WeakReference atual.

GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Aplica-se a

Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Confira também