Weak Reference

  • Thread starter Thread starter Ahlompys
  • Start date Start date
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...
 

Similar threads

P
Replies
0
Views
176
Policy standard local admin account with Active Di
P
Back
Top