如何计算已处置的对象取决于您的实现,但您可以获得GC Notifications
.
垃圾收集通知
这在 .NET 3.5 SP1 中引入了 GC,以在 GC 收集即将开始并且 GC 收集成功完成时生成通知。因此,如果您处于应用程序的资源密集型阶段,GC 通知将允许您收到 GC 即将到来的通知,以便您可以停止当前进程并等待 GC 完成。这使您的应用程序能够顺利运行。
获取 GC 通知的步骤:
- 当 GC 接近时调用
GC.RegisterForFullGCNotification
以允许通知。
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);
}
}
}
参考:.NET 4.0 中的垃圾收集通知