Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleUse the WeakReference class in VB .NET
DescriptionThis example shows how to use the WeakReference class in VB .NET. WeakReference lets a program hold a reference to an object that it is willing to give up if the garbage collector runs.
KeywordsWeakReference, garbage collection, garbage collector, VB.NET
CategoriesVB.NET, Software Engineering
 
A WeakReference holds a reference to an object. If the garbage collector runs, it releases the reference. You can use this to hold on to objects that you may want later but that you can release when memory runs low.

The MemoryHog class simply grabs a bunch of memory.

 
Public Class MemoryHog
    Public Memory(99999) As Integer
    ' Initialize the memory.
    Public Sub New()
        For i As Integer = 0 To Memory.GetUpperBound(0)
            Memory(i) = i
        Next i
    End Sub
End Class
 
When you click the Create button, the program makes new instances of the MemoryHog class. It stores WeakReferences to those objects. When you allocate enough MemoryHogs, the garbage collector runs and reclaims the existing MemoryHogs.

After it allocates the new MemoryHogs, possibly causing garbage collection, the program sees which objects are still alive. The program shows how to access objects that are still living.

 
Private m_Objects() As WeakReference
Private m_NumObjects As Integer = 0

Private Sub btnCreate_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnCreate.Click
    ' See how many new objects to create.
    Dim new_objects As Integer = _
        Integer.Parse(txtNumObjects.Text)

    ' Make room.
    ReDim Preserve m_Objects(m_NumObjects + new_objects)

    ' Make the objects.
    For i As Integer = 1 To new_objects
        m_Objects(m_NumObjects) = _
            New WeakReference(New MemoryHog)
        m_NumObjects += 1
    Next i

    ' Display statistics.
    lblTotalObjects.Text = m_NumObjects.ToString
    Dim objects_alive As Integer = 0
    For i As Integer = 0 To m_NumObjects - 1
        ' See if this object is alive.
        ' Can also use: 
        '     If Not (m_Objects(i).Target Is Nothing) Then
        If m_Objects(i).IsAlive Then
            ' It's alive!
            objects_alive += 1

            ' Turn it back into a MemoryHog.
            Dim memory_hog As MemoryHog = _
                DirectCast(m_Objects(i).Target, MemoryHog)
            ' Use it.
            Debug.WriteLine(memory_hog.Memory(i))
        End If
    Next i
    Debug.WriteLine("==========")
    lblObjectsAlive.Text = objects_alive.ToString
    lblObjectsDead.Text = (m_NumObjects - _
        objects_alive).ToString
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated