破棄されたオブジェクトをカウントする方法は、実装によって異なりますが、を取得できますGC Notifications
。
ガベージコレクションの通知
これは、.NET 3.5 SP1のGCで導入され、GC収集が開始され、GC収集が正常に完了するたびに通知を生成します。したがって、アプリケーションの非常にリソースを消費するフェーズの間にある場合、GC通知を使用すると、GCが近づいていることを通知できるため、現在のプロセスを停止して、GCが完了するのを待つことができます。これにより、アプリケーションがスムーズに実行されます。
GC通知を取得するための手順:
GC.RegisterForFullGCNotification
GCが近づいたときに通知を許可するために呼び出します。
GC.WaitForFullGCApproach
アプリケーションから新しいスレッドを作成し、メソッドやメソッドへの無限ループで継続的にポーリングを開始しGC.WaitForFullGCComplete
ます。
GCNotificationStatus.Succeeded
通知を発行する必要がある場合は、両方のメソッドが戻ります。
- 呼び出しスレッド
GC.CancelFullGCNotification
で、通知プロセスの登録を解除するために使用します。
サンプルコードの実装
public class MainProgram
{
public static List<char[]> lst = new List<char[]>();
public static void Main(string[] args)
{
try
{
// Register for a notification.
GC.RegisterForFullGCNotification(10, 10);
// Start a thread using WaitForFullGCProc.
Thread startpolling = new Thread(() =>
{
while (true)
{
// Check for a notification of an approaching collection.
GCNotificationStatus s = GC.WaitForFullGCApproach(1000);
if (s == GCNotificationStatus.Succeeded)
{
//Call event
Console.WriteLine("GC is about to begin");
GC.Collect();
}
else if (s == GCNotificationStatus.Canceled)
{
// Cancelled the Registration
}
else if (s == GCNotificationStatus.Timeout)
{
// Timeout occurred.
}
// Check for a notification of a completed collection.
s = GC.WaitForFullGCComplete(1000);
if (s == GCNotificationStatus.Succeeded)
{
//Call event
Console.WriteLine("GC has ended");
}
else if (s == GCNotificationStatus.Canceled)
{
//Cancelled the registration
}
else if (s == GCNotificationStatus.Timeout)
{
// Timeout occurred
}
Thread.Sleep(500);
}
});
startpolling.Start();
//Allocate huge memory to apply pressure on GC
AllocateMemory();
// Unregister the process
GC.CancelFullGCNotification();
}
catch { }
}
private static void AllocateMemory()
{
while (true)
{
char[] bbb = new char[1000]; // creates a block of 1000 characters
lst.Add(bbb); // Adding to list ensures that the object doesnt gets out of scope
int counter = GC.CollectionCount(2);
Console.WriteLine("GC Collected {0} objects", counter);
}
}
}
参照:.NET4.0でのガベージコレクションの通知