I have another C# theory question I am hoping I can get some clarity on, I have seen a few WeakReference samples around but they never work for me but I've read in some people's comments and articles that the samples work for them. I am battling to find out why these samples are not working for me. I can't tell if it is non-deterministic behavior of GC.Collect(), which I'm also battling to establish if that is even applicable. This is the code I'm working on at the moment but I have tried numerous others directly from tutorials that illustrate the concept as well:
class Program
{
static WeakReference _weak;
static void Main(string[] args)
{
_weak = new WeakReference(new WeakClass { Name = "Matthew" });
if (_weak.IsAlive)
{
Console.WriteLine((_weak.Target as WeakClass).ToString());
}
GC.Collect();
if (_weak.IsAlive)
{
Console.WriteLine("IsAlive"); // This is always being printed when, according to the articles, it shouldn't be
}
Console.WriteLine("[Done]");
Console.Read();
}
}
class WeakClass
{
public string Name { get; set; }
public override string ToString()
{
return this.Name;
}
~WeakClass()
{
Console.WriteLine(string.Format("{0} got destructed...", this.Name));
}
}
The WeakRerence is always still alive after I call GC.Collect(). I've also tried adding calls to GC.WaitForFullGCComplete() and GC.WaitForPendingFinalizers() as well with no joy.