我有一个持有代表的课程,以便稍后懒洋洋地评估一些事情.
一旦我评估了它,通过调用委托,我清除了对委托的引用,希望它有资格收集.毕竟,如果将它构造为匿名方法,它可能会保留一个局部变量的世界.
我尝试构建一个单元测试来验证这一点,但它似乎没有按照我计划的方式运行,而是看起来我的假设WeakReference(我在这里用于测试目的),或者其他一些假设,都没有.拿水.
看看这段代码,你可以在LINQPad中运行它
void Main()
{
WeakReference wr;
Lazy<int> l;
CreateTestData(out wr, out l);
wr.IsAlive.Dump(); // should be alive here
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
wr.IsAlive.Dump(); // and alive here as well
l.Value.Dump(); // but now we clear the reference
GC.Collect(); // so one of these should collect it
GC.WaitForPendingFinalizers();
GC.Collect();
wr.IsAlive.Dump(); // and then it should be gone here
GC.KeepAlive(l);
}
void CreateTestData(out WeakReference wr, out Lazy<int> l)
{
Func<int> f = () => 10;
wr …Run Code Online (Sandbox Code Playgroud)