System Namespace


.NET Framework Class Library
WeakReference Class

Represents a weak reference, which references an object while still allowing that object to be reclaimed by garbage collection.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
<SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags := SecurityPermissionFlag.UnmanagedCode)> _
Public Class WeakReference _
    Implements ISerializable
Visual Basic (Usage)
Dim instance As WeakReference
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
JScript
public class WeakReference implements ISerializable
Remarks

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.

Examples

The following example demonstrates how you can use weak references to maintain a cache of objects as a resource for an application. The cache is constructed using an IDictionary<(Of <(TKey, TValue>)>) of WeakReference objects keyed by an index value. 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.

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%
//
.NET Framework Security

Inheritance Hierarchy

System..::.Object
  System..::.WeakReference
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0
See Also

Reference

Other Resources

Tags :


Community Content

_VMI
Data indexer getter doesn't cache regenerated data?!?

Please post additional content here, not questions.

Tags : contentbug

verdy.p
For a more convincing example
See http://msdn.microsoft.com/en-us/library/system.collections.icomparer.compare(classic).aspx
which includes an example that uses a single WeakReference (in a thread-local static ) to cache (in its Target property) a reference to an instance of an ICompare object, that can be reused across many calls to the Compare() method of a custom ICompare implementation class and then delegate to it.

Using WeakReferences is typical within many apps where the initialization of objects is costly, uses too much memory, can take long and cumulative time for application startup, and it is preferable to allocating a delegate at each invokation (this would sollicitate the GC too often), and even preferable to using a single non thread-local static reference (that would need to be protected in order to be used in a thread-safe way, using costly mutex locks, and that would survive in memory longer than necessary, when it is no longer used or other more urgent memory use is needed elsewhere in your application).

There are really a lot of usage patterns where WeakReference will be used with [ThreadStatic] caches: it really improves the performance if it is used consistantly.
Tags :

Page view tracker