Export (0) Print
Expand All

WeakReference Class

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

System.Object
  System.WeakReference

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

'Declaration
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
<SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags := SecurityPermissionFlag.UnmanagedCode)> _
Public Class WeakReference _
	Implements ISerializable

The WeakReference type exposes the following members.

  NameDescription
Protected methodWeakReference
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsWeakReference(Object)Initializes a new instance of the WeakReference class, referencing the specified object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsWeakReference(Object, Boolean)Initializes a new instance of the WeakReference class, referencing the specified object and using the specified resurrection tracking.
Protected methodWeakReference(SerializationInfo, StreamingContext)Initializes a new instance of the WeakReference class, using deserialized data from the specified serialization and stream objects.
Top

  NameDescription
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIsAliveGets an indication whether the object referenced by the current WeakReference object has been garbage collected.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsTargetGets or sets the object (the target) referenced by the current WeakReference object.
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsTrackResurrectionGets an indication whether the object referenced by the current WeakReference object is tracked after it is finalized.
Top

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsFinalizeDiscards the reference to the target represented by the current WeakReference object. (Overrides Object.Finalize.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetObjectDataPopulates a SerializationInfo object with all the data needed to serialize the current WeakReference object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToStringReturns a string that represents the current object. (Inherited from Object.)
Top

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

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 = "" 
        GC.Collect(0)

        ' 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
        Next  

        ' 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)))
        Next 
    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  

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

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

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