【发布时间】:2015-05-06 12:52:07
【问题描述】:
我想计算垃圾收集需要多长时间。
根据这些文章:
- https://msdn.microsoft.com/en-us/library/cc713687(v=vs.110).aspx
- http://www.codeproject.com/Articles/101136/Garbage-Collection-Notifications-in-NET
我想出了下面的代码。这是在 C# 中计算垃圾收集时间的正确方法吗?
class Program
{
public static void Main(string[] args)
{
var done = false;
var load = new List<byte[]>();
var pollGC = new Action(() =>
{
// Register for a notification.
GC.RegisterForFullGCNotification(10, 10);
Console.WriteLine("Registered for GC notification.");
Stopwatch gcTimer = new Stopwatch();
while (!done)
{
// Check for a notification of an approaching collection.
GCNotificationStatus s = GC.WaitForFullGCApproach();
if (s == GCNotificationStatus.Succeeded)
{
Console.WriteLine("GC is about to start.");
load.Clear();
gcTimer.Restart();
}
// Check for a notification of a completed collection.
s = GC.WaitForFullGCComplete();
if (s == GCNotificationStatus.Succeeded)
{
Console.WriteLine("GC has finished in {0} ms", gcTimer.ElapsedMilliseconds);
}
Thread.Sleep(500);
}
GC.CancelFullGCNotification();
Console.WriteLine("Finished monitoring GC");
});
var doWork = new Action(() =>
{
while (!done)
{
try
{
load.Add(new byte[10000]);
}
catch (OutOfMemoryException)
{
Console.WriteLine("Out of memory. {0}", load.Count);
}
}
});
Console.WriteLine(GCSettings.IsServerGC);
Task.Run(pollGC);
Task.Run(doWork);
Console.ReadLine();
done = true;
GC.CancelFullGCNotification();
Thread.Sleep(2000);
}
}
【问题讨论】:
-
与论坛网站不同,我们不使用“谢谢”、“感谢任何帮助”或Stack Overflow 上的签名。请参阅“Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?.
标签: c# .net garbage-collection instrumentation