您的示例不是内存泄漏,您将耗尽内存,但您创建的所有对象都可以被正在运行的程序访问。泄漏是指内存中有无法访问的对象。以下是 .NET 中最常见的泄漏原因示例,订阅静态事件:
internal class Program
{
public static event EventHandler SomeStaticEvent;
private static void Main()
{
while (true)
{
var a = new A();
//here a goes out of scope but won't be collected by GC because Program still holds reference to "a" by a static event subsription
}
}
public class A
{
public A()
{
//if you comment this line, there is no reference from Program to A and a will be GC-ed and memory allocated will be released
Program.SomeStaticEvent+=ProgramOnSomeStaticEvent;
}
private void ProgramOnSomeStaticEvent(object sender, EventArgs eventArg){}
}
}
订阅静态事件或长寿对象的事件时要小心。您的程序正在泄漏,并且不容易发现原因。始终在对象超出范围之前取消订阅此类事件。