Classe WeakReference (System)

Cambia visualizzazione:
ScriptFree
Riferimento a .NET Framework
Classe WeakReference
Il presente articolo è stato tradotto manualmente. Per visualizzare questa pagina e contemporaneamente visualizzarne il contenuto in lingua inglese, passare alla visualizzazione semplificata.

Rappresenta un riferimento debole, ovvero un riferimento a un oggetto che può ancora essere recuperato dalla procedura di Garbage Collection.

Gerarchia di ereditarietà

System.Object
  System.WeakReference

Spazio dei nomi:  System
Assembly:  mscorlib (in mscorlib.dll)
Sintassi

Visual Basic
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
<SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags := SecurityPermissionFlag.UnmanagedCode)> _
Public Class WeakReference _
	Implements ISerializable
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public class WeakReference : ISerializable
Visual C++
[SerializableAttribute]
[ComVisibleAttribute(true)]
[SecurityPermissionAttribute(SecurityAction::InheritanceDemand, Flags = SecurityPermissionFlag::UnmanagedCode)]
public ref class WeakReference : ISerializable
F#
[<SerializableAttribute>]
[<ComVisibleAttribute(true)>]
[<SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)>]
type WeakReference =  
    class
        interface ISerializable
    end

Il tipo WeakReference espone i seguenti membri.

Costruttori

  Nome Descrizione
Metodo pubblico Supportato da XNA Framework hbh8w2zd.PortableClassLibrary(it-it,VS.100).gif WeakReference(Object) Consente di inizializzare una nuova istanza della classe WeakReferenceche fa riferimento all'oggetto specificato.
Metodo pubblico Supportato da XNA Framework hbh8w2zd.PortableClassLibrary(it-it,VS.100).gif WeakReference(Object, Boolean) Consente di inizializzare una nuova istanza della classe WeakReference, che fa riferimento all'oggetto specificato e utilizza la traccia di ripristino specificata.
Metodo protetto WeakReference(SerializationInfo, StreamingContext) Consente di inizializzare una nuova istanza della classe WeakReference, utilizzando dati deserializzati dalla serializzazione e dagli oggetti del flusso specificati.
In alto
Proprietà

  Nome Descrizione
Proprietà pubblica Supportato da XNA Framework hbh8w2zd.PortableClassLibrary(it-it,VS.100).gif IsAlive Indica se l'oggetto cui fa riferimento l'oggetto WeakReference corrente è stato sottoposto alla procedura di Garbage Collection.
Proprietà pubblica Supportato da XNA Framework hbh8w2zd.PortableClassLibrary(it-it,VS.100).gif Target Ottiene o imposta l'oggetto o la destinazione a cui fa riferimento l'oggetto WeakReference corrente.
Proprietà pubblica Supportato da XNA Framework hbh8w2zd.PortableClassLibrary(it-it,VS.100).gif TrackResurrection Ottiene un'indicazione che specifica se l'oggetto cui fa riferimento l'oggetto WeakReference corrente viene controllato dopo essere stato finalizzato.
In alto
Metodi

  Nome Descrizione
Metodo pubblico Supportato da XNA Framework hbh8w2zd.PortableClassLibrary(it-it,VS.100).gif Equals(Object) Determina se l'oggetto Object specificato è uguale all'oggetto Object corrente. (Ereditato da Object)
Metodo protetto Supportato da XNA Framework hbh8w2zd.PortableClassLibrary(it-it,VS.100).gif Finalize Elimina il riferimento alla destinazione rappresentata dall'oggetto WeakReference corrente. (Esegue l'override di Object.Finalize()).
Metodo pubblico Supportato da XNA Framework hbh8w2zd.PortableClassLibrary(it-it,VS.100).gif GetHashCode Funge da funzione hash per un determinato tipo. (Ereditato da Object)
Metodo pubblico GetObjectData Compila un oggetto SerializationInfo con tutti i dati necessari per serializzare l'oggetto WeakReference corrente.
Metodo pubblico Supportato da XNA Framework hbh8w2zd.PortableClassLibrary(it-it,VS.100).gif GetType Ottiene l'oggetto Type dell'istanza corrente. (Ereditato da Object)
Metodo protetto Supportato da XNA Framework hbh8w2zd.PortableClassLibrary(it-it,VS.100).gif MemberwiseClone Consente di creare una copia dei riferimenti dell'oggetto Object corrente. (Ereditato da Object)
Metodo pubblico Supportato da XNA Framework hbh8w2zd.PortableClassLibrary(it-it,VS.100).gif ToString Restituisce una stringa che rappresenta l'oggetto corrente. (Ereditato da Object)
In alto
Note

Un riferimento debole consente al Garbage Collector di raccogliere un oggetto consentendo comunque a un'applicazione di accedere all'oggetto. Se l'oggetto è necessario, è comunque possibile ottenere un riferimento forte ad esso e impedire che venga raccolto. Per ulteriori informazioni sull'utilizzo di riferimenti deboli brevi e lunghi, vedere Riferimenti deboli.

Esempi

Nell'esempio seguente viene dimostrato come l'impiego di riferimenti deboli consenta di gestire una cache di oggetti utilizzandola come risorsa per un'applicazione. La cache viene costruita utilizzando un oggetto IDictionary<TKey, TValue> di oggetti WeakReference ai quali viene applicato un valore di indice che funge da chiave. La proprietà Target degli oggetti WeakReference è un oggetto in una matrice di byte che rappresenta dati.

Nell'esempio l'accesso agli oggetti contenuti nella cache avviene in modo casuale. Se un oggetto viene recuperato per Garbage Collection, viene rigenerato un nuovo oggetto dati. In caso contrario l'oggetto è disponibile per l'accesso a causa del riferimento debole.

Visual Basic

Imports System
Imports System.Collections.Generic
Public Class Module1

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

        ' Randomly access objects in the cache.
        Dim i As Integer
        Do While i < c.Count
            Dim index As Integer = r.Next(c.Count)

            ' Access the object by
            ' getting a property value.
            DataName = c(index).Name

            i += 1
        Loop

        'Show results.
        Dim regenPercent As Double = c.RegenerationCount * 100 / c.Count
        Console.WriteLine("Cache size: {0}, Regenerated: {1}%", c.Count.ToString(), regenPercent.ToString())

    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)
        MyBase.New()
        _cache = New Dictionary(Of Integer, WeakReference)

        ' Add data objects with a short
        ' weak reference to the cache.
        Dim i As Integer = 0
        Do While (i < count)
            _cache.Add(i, New WeakReference(New Data(i)))
            i = (i + 1)
        Loop
    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

    ' Access a data object from the cache.
    ' If the object was reclaimed for garbage collection,
    ' create a new data object at that index location.
    Default Public ReadOnly Property Item(ByVal index As Integer) As Data
        Get
            ' Obtain an instance of a data
            ' object from the cache of
            ' of weak reference objects.
            Dim d As Data = CType(_cache(index).Target, Data)
            If (d Is Nothing) Then
                ' Object was reclaimed, so generate a new one.
                Console.WriteLine("Regenerate object at {0}: Yes", index.ToString())
                d = New Data(index)
                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)
        MyBase.New()
        _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%
'


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

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


Informazioni sulla versione

.NET Framework

Supportato in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supportato in: 4, 3.5 SP1

Supportato in:
Sicurezza di .NET Framework

Piattaforme

Windows 7, Windows Vista SP1 o versione successiva, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (componenti di base del server non supportati), Windows Server 2008 R2 (componenti di base del server supportati con SP1 o versione successiva), Windows Server 2003 SP2

.NET Framework non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema di .NET Framework.
Codice thread safe

Qualsiasi membro static (Shared in Visual Basic) pubblico di questo tipo è thread-safe. I membri di istanza non sono garantiti come thread-safe.
Vedere anche

Riferimenti

GC

Altre risorse