I'm preparing for MS exam Programming in C# ExamRef 70-483
and reading book with the same name. There is chapter about using WeakReference
and following example:
using System;
using System.Drawing;
class Program
{
static WeakReference data;
static void Main()
{
object result = GetData();
GC.Collect();
result = GetData();
}
private static object GetData()
{
if (data == null)
{
data = new WeakReference(LoadLargeData());
}
if (data.Target == null)
{
data.Target = LoadLargeData();
}
return data.Target;
}
private static object LoadLargeData()
{
return new Bitmap(20000, 20000);
}
}
The only change I've done is LoadLargeData()
implementation, in the book there is LoadLargeList()
without implementation.
The problem is, that after invoking GC.Collect()
, my data.Target
is never null
. How can I force GC to really collect this WeakReference
data?