我在谷歌上搜索没有得到我想要的。我不知道我是对还是错。看,我试图理解 GC.Collect() 所以这里是代码..
public class SomePublisher
{
public event EventHandler SomeEvent;
}
public class SomeSubscriber
{
public static int Count;
public SomeSubscriber(SomePublisher publisher)
{
publisher.SomeEvent += new EventHandler(publisher_SomeEvent);
}
~SomeSubscriber()
{
SomeSubscriber.Count++;
}
private void publisher_SomeEvent(object sender, EventArgs e)
{
// TODO: something
}
}
我在我的主线程中这样做..
SomePublisher publisher = new SomePublisher();
for (int i = 0; i < 10; i++)
{
SomeSubscriber subscriber = new SomeSubscriber(publisher);
subscriber = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine(SomeSubscriber.Count.ToString());
Console.ReadLine();
我得到输出 0,但根据我的说法应该是 10,因为 GC.Collect() 必须从内存中删除 class1 对象,因此必须调用 class1 析构函数,因此计数必须增加到 10 ..任何人都可以解释这一点..