承接前文 GC 基礎與關鍵方法,本文聚焦 .NET 4.0 引入的背景式 GC (Background GC) 與完整 GC 通知 API。
基於 Workstation GC with Concurrent 模式演進:
四個靜態方法:
GC.RegisterForFullGCNotification(maxGenThreshold, lohThreshold):註冊通知,參數為 Gen 2 存活物件數與 LOH 物件數閾值。GC.WaitForFullGCApproach():阻塞等待 Full GC 即將開始,回傳 GCNotificationStatus.Succeeded 時可暫停人工 GC.Collect() 避免干擾。GC.WaitForFullGCComplete():阻塞等待 Full GC 完成,完成後可恢復高負載配置。GC.CancelFullGCNotification():取消註冊。static bool checkForNotify = false, bAllocate = false, finalExit = false;
static List<byte[]> load = new List<byte[]>();
public static void Main() {
try {
GC.RegisterForFullGCNotification(10, 10);
checkForNotify = true; bAllocate = true;
new Thread(WaitForFullGCProc).Start();
// 模擬伺服器負載配置
while (true) {
if (bAllocate) { load.Add(new byte[1000]); /* 監控 Gen 2 次數 */ }
if (finalExit) break;
}
} catch (InvalidOperationException) { /* Concurrent GC 啟用時不支援通知 */ }
finally { GC.CancelFullGCNotification(); }
}
static void WaitForFullGCProc() {
while (checkForNotify) {
var s = GC.WaitForFullGCApproach();
if (s == GCNotificationStatus.Succeeded) { bAllocate = false; /* 暫停配置 */ }
s = GC.WaitForFullGCComplete();
if (s == GCNotificationStatus.Succeeded) { bAllocate = true; /* 恢復配置 */ }
}
}
適用於高併發伺服器:在 Full GC 期間暫停新請求配置,降低延遲尖峰。