あなたの例はメモリリークではありません。メモリが不足しますが、作成されたすべてのオブジェクトは実行中のプログラムからアクセスできます。リークとは、メモリ内にアクセスできないオブジェクトがある場合です。.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){}
}
}
静的イベントへのサブスクリプション、または長期間存続するオブジェクトのイベントへのサブスクリプションには注意してください。あなたのプログラムはリークしており、その理由を見つけるのは簡単ではありません. オブジェクトが範囲外になる前に、常にそのようなイベントからサブスクライブを解除してください。