A
Ahlompys
Guest
static WeakReference data;
static object GetData()
{
if(data == null) { data = new WeakReference(GetList()); }
if(data.Target == null) { data.Target = GetList(); }
return data.Target;
}
static private ICollection<string> GetList()
{
return new List<string> { "Hello", " Word"};
}
When I do this all work Like I think
GetData();
Console.WriteLine($"{data.Target}");// Not Null
Console.WriteLine($"{data.IsAlive}");// True
Console.WriteLine();
GC.Collect();
Console.WriteLine($"{data.Target}");//Null
Console.WriteLine($"{data.IsAlive}");//False
But When I Write this.
GetData();
Console.WriteLine($"{data.Target}");// Not Null
Console.WriteLine($"{data.IsAlive}");// True
Console.WriteLine();
GC.Collect();
Console.WriteLine($"{data.Target}");//Not Null
Console.WriteLine($"{data.IsAlive}");//TRUE
varobj = GetData();
foreach (var item in (ICollection<string>)obj)
{
Console.WriteLine(item);
}
Console.WriteLine();
GC.Collect();
Console.WriteLine($"{data.Target}");//NOT NULL
Console.WriteLine($"{data.IsAlive}");//TRUE
foreach (var item in (ICollection<string>)obj)
{
Console.WriteLine(item);//Hello World
}
I see another situation WHY?
Continue reading...