Weak References, when to use?

Weak Reference per MSDN:

“weak reference, … references an object while still allowing it to be garbage collected.”

I’d like to hear your experience with using Weak References. What were the circumstances? Was it worth the extra work involved? Etc…

 

MSDN Weak Reference:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemweakreferenceclasstopic.asp

http://msdn.microsoft.com/en-us/library/system.weakreference.aspx

http://msdn.microsoft.com/en-us/library/ms404247.aspx

 

Update:

Well that sucks... I just realized that all of the comments received on this subject were removed in the upgrade. I'll try and summarize the responses and my subsequent use of Weak References since this posting:

 

The general thinking is that you only use Weak References when you are dealing with large chunks of data that can be easily recreated, such as multimedia content. While a weak reference can be an appealing option for automatic memory management, it should only be used if a caching solution doesn't work.

 

Here is an example where Weak References would be helpful:

 

You have a form that displays a huge picture as the background. Now let’s say that you show another window that obstructs the view of the original window and the picture is not seen at all. Why have the picture stored in memory if it’s not being used?

 

If you create a pointer to the picture using a Weak Reference, and another part of your program needs to use a significant amount of memory, the Garbage Collector can now release the memory that was being used by the picture and use it for the active operation.

 

When you return to the main screen, you can simply reload the image from disk like nothing happened.

 

Here is some code to help:

 

Public Class Form1

    Const IMAGE_FILENAME As String = "C:\MyPicture.jpg"

 

    Private _imgPTR As New WeakReference(Image.FromFile(IMAGE_FILENAME), False)

 

    Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)

        If Not _imgPTR.IsAlive Then

            _imgPTR.Target = Image.FromFile(IMAGE_FILENAME)

        End If

 

        e.Graphics.DrawImage(DirectCast(_imgPTR.Target, Image), Me.ClientRectangle)

        MyBase.OnPaint(e)

    End Sub

 

    Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click

        DirectCast(_imgPTR.Target, Image).Dispose()

        GC.Collect()

    End Sub

End Class

 

No Comments