Duration (Pacific Standard Time):
To (Pacific Standard Time):
  • None
User Action:
  • None

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)


	Flags := SecurityPermissionFlag.UnmanagedCode)>
Public Class WeakReference
	Implements ISerializable
Name Description
System_CAPS_pubmethod WeakReference(Object)

Initializes a new instance of the WeakReference class, referencing the specified object.

System_CAPS_pubmethod WeakReference(Object, Boolean)

Initializes a new instance of the WeakReference class, referencing the specified object and using the specified resurrection tracking.

System_CAPS_protmethod WeakReference(SerializationInfo, StreamingContext)

Initializes a new instance of the WeakReference class, using deserialized data from the specified serialization and stream objects.

Name Description
System_CAPS_pubproperty IsAlive

Gets an indication whether the object referenced by the current WeakReference object has been garbage collected.

System_CAPS_pubproperty Target

Gets or sets the object (the target) referenced by the current WeakReference object.

System_CAPS_pubproperty TrackResurrection

Gets an indication whether the object referenced by the current WeakReference object is tracked after it is finalized.

Name Description
System_CAPS_pubmethod Equals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_protmethod Finalize()

Discards the reference to the target represented by the current WeakReference object.(Overrides Object.Finalize().)

System_CAPS_pubmethod GetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethod GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo object with all the data needed to serialize the current WeakReference object.

System_CAPS_pubmethod GetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_protmethod MemberwiseClone()

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_pubmethod ToString()

Returns a string that represents the current object.(Inherited from Object.)

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.

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<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.

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

        ' 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

        ' 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)))
    End Sub 

    ' Number of items in the cache. 
    Public ReadOnly Property Count() As Integer 
            Return _cache.Count
        End Get 
    End Property 

    ' Number of times an object needs to be regenerated. 
    Public ReadOnly Property RegenerationCount() As Integer 
            Return regenCount
        End Get 
    End Property 

    ' Retrieve a data object from the cache. 
    Default Public ReadOnly Property Item(ByVal index As Integer) As Data
            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
                ' 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 
            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% 

for the ability to call unmanaged code. Demand value: InheritanceDemand; Permission value: UnmanagedCode

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1

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

Return to top