Can anyone explain what happens here?
delegate void TestDelegate(string val);
class Program
{
static void Main(string[] args)
{
Test p = new Test();
string s = "Main";
TestDelegate strongRef = (val) =>
{
Console.WriteLine(val + ": " + s);
};
p.AssignLambda(strongRef);
while (true)
{
p.CallLambda();
Thread.Sleep(1000);
System.GC.Collect();
}
}
}
class Test
{
WeakReference _ref;
internal void AssignLambda(TestDelegate del)
{
_ref = new WeakReference(del);
}
internal void CallLambda()
{
TestDelegate del = _ref.Target as TestDelegate;
if (del != null)
{
del("Delegate Alive");
}
else
{
Console.WriteLine("Delegate Dead");
}
}
}
I am expecting "Delegate Alive: Main" to get printed continuously. But I get "Delegate Dead" printed continuously.
Note: I compile this as 64 bit application. It works fine as expected if I compile it as 32 bit Application.
Compiler: VS 2012, Target Framework: .NET 4.0, OS: Win 7 64 bit professional