Este artículo se tradujo de forma manual. Mueva el puntero sobre las frases del artículo para ver el texto original.
Traducción
Original
Personas que lo han encontrado útil: 0 de 1 - Valorar este tema

WeakReference (Clase)

Representa una referencia débil, que hace referencia a un objeto mientras sigue permitiendo que la recolección de elementos no utilizados lo reclame.

System.Object
  System.WeakReference

Espacio de nombres:  System
Ensamblado:  mscorlib (en mscorlib.dll)
[SerializableAttribute]
[ComVisibleAttribute(true)]
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public class WeakReference : ISerializable

El tipo WeakReference expone los siguientes miembros.

  Nombre Descripción
Método público Compatible con XNA Framework hbh8w2zd.PortableClassLibrary(es-es,VS.100).gif WeakReference(Object) Inicializa una nueva instancia de la clase WeakReference que hace referencia al objeto especificado.
Método público Compatible con XNA Framework hbh8w2zd.PortableClassLibrary(es-es,VS.100).gif WeakReference(Object, Boolean) Inicializa una nueva instancia de la clase WeakReference que hace referencia al objeto especificado y utiliza el seguimiento especificado del restablecimiento.
Método protegido WeakReference(SerializationInfo, StreamingContext) Inicializa una nueva instancia de la clase WeakReference utilizando datos sin serializar de la serialización y objetos de secuencia especificados.
Arriba
  Nombre Descripción
Propiedad pública Compatible con XNA Framework hbh8w2zd.PortableClassLibrary(es-es,VS.100).gif IsAlive Obtiene un valor que indica si el objeto al que hace referencia el objeto WeakReference actual ha sido detectado durante la recolección de elementos no utilizados.
Propiedad pública Compatible con XNA Framework hbh8w2zd.PortableClassLibrary(es-es,VS.100).gif Target Obtiene o establece el objeto (destino) al que hace referencia el objeto WeakReference actual.
Propiedad pública Compatible con XNA Framework hbh8w2zd.PortableClassLibrary(es-es,VS.100).gif TrackResurrection Obtiene un valor que indica si se debe realizar un seguimiento del objeto al que hace referencia el objeto WeakReference actual después de su finalización.
Arriba
  Nombre Descripción
Método público Compatible con XNA Framework hbh8w2zd.PortableClassLibrary(es-es,VS.100).gif Equals(Object) Determina si el objeto Object especificado es igual al objeto Object actual. (Se hereda de Object).
Método protegido Compatible con XNA Framework hbh8w2zd.PortableClassLibrary(es-es,VS.100).gif Finalize Descarta la referencia al destino representado por el objeto WeakReference actual. (Invalida a Object.Finalize()).
Método público Compatible con XNA Framework hbh8w2zd.PortableClassLibrary(es-es,VS.100).gif GetHashCode Actúa como función hash para un tipo concreto. (Se hereda de Object).
Método público GetObjectData Rellena un objeto SerializationInfo con todos los datos necesarios para serializar el objeto WeakReference actual.
Método público Compatible con XNA Framework hbh8w2zd.PortableClassLibrary(es-es,VS.100).gif GetType Obtiene el objeto Type de la instancia actual. (Se hereda de Object).
Método protegido Compatible con XNA Framework hbh8w2zd.PortableClassLibrary(es-es,VS.100).gif MemberwiseClone Crea una copia superficial del objeto Object actual. (Se hereda de Object).
Método público Compatible con XNA Framework hbh8w2zd.PortableClassLibrary(es-es,VS.100).gif ToString Devuelve una cadena que representa el objeto actual. (Se hereda de Object).
Arriba

Una referencia débil permite al recolector de elementos no utilizados recopilar un objeto mientras sigue permitiendo que una aplicación tenga acceso a éste. Si necesita el objeto, aún puede obtener una referencia fuerte a él y evitar que se recopile. Para obtener más información sobre cómo utilizar referencias débiles cortas y largas, vea Referencias parciales.

En el ejemplo siguiente se muestra cómo puede utilizar referencias débiles para mantener una caché de objetos como un recurso para una aplicación. La caché se construye utilizando una interfaz IDictionary<TKey, TValue> de objetos WeakReference con clave de valor de índice. La propiedad Target de los objetos WeakReference es un objeto de una matriz de bytes que representa datos.

El ejemplo obtiene acceso de forma aleatoria a los objetos de la caché. Si se reclama un objeto para la recolección de elementos no utilizados, vuelve a generarse un nuevo objeto de datos; de lo contrario, el objeto estará disponible para su acceso debido a la referencia débil.


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 = "";

        // 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 * 100 / c.Count;
        Console.WriteLine("Cache size: {0}, Regenerated: {1}%", c.Count.ToString(), regenPercent.ToString());

    }
}


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

    }

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

    // Returns the number of times an 
    // object had to be regenerated.
    public int RegenerationCount
    {
        get
        {
            return regenCount;
        }
    }

    // Accesses a data object from the cache.
    // If the object was reclaimed for garbage collection,
    // create a new data object at that index location.
    public Data this[int index]
    {
        get
        {
            // Obtain an instance of a data
            // object from the cache of
            // of weak reference objects.
            Data d = _cache[index].Target as Data;
            if (d == null)
            {
                // Object was reclaimed, so generate a new one.
                Console.WriteLine("Regenerate object at {0}: Yes", index.ToString());
                d = new Data(index);
                regenCount++;
            }
            else
            {
                // Object was obtained with the weak reference.
                Console.WriteLine("Regenerate object at {0}: No", index.ToString());
            }

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


.NET Framework

Compatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Compatible con:

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Todos los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.
¿Le ha resultado útil?
(Caracteres restantes: 1500)
Contenido de la comunidad Agregar