如何在 C# 中強制執行垃圾回收?
是的,透過呼叫 Collect() 方法可以強制 C# 中的垃圾回收器執行
這不算什麼好習慣,因為它可能會造成效能開銷。Collect() 會強制對所有世代進行立即垃圾回收。
Collect(Int32)強制從第 0 世代進行垃圾回收到指定的某個世代。
示例
using System; class MyGCCollectClass{ private const int maxGarbage = 1000; static void Main(){ // Put some objects in memory. MyGCCollectClass.MakeSomeGarbage(); Console.WriteLine("Memory used before collection: {0:N0}", GC.GetTotalMemory(false)); // Collect all generations of memory. GC.Collect(); Console.WriteLine("Memory used after full collection: {0:N0}", GC.GetTotalMemory(true)); } static void MakeSomeGarbage(){ Version vt; // Create objects and release them to fill up memory with unused objects. for(int i = 0; i < maxGarbage; i++){ vt = new Version(); } } }
廣告