예, 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();
}
}
}