使用這個方法嘗試回收無法存取的所有記憶體。然而,Collect 方法不保證回收所有無法存取的記憶體。
不論物件已經在記憶體中存留多久,所有的物件都將視為可回收;然而,在 Managed 程式碼中參考的物件則不會回收。使用這個方法來強制系統嘗試回收可用記憶體的最大量。
Demo 1:
static void Main() { // Put some objects in memory. MyGCCollectClass.MakeSomeGarbage(); Console.WriteLine("Memory used before collection: {0}", GC.GetTotalMemory(false)); // Collect all generations of memory. GC.Collect(); Console.WriteLine("Memory used after full collection: {0}", GC.GetTotalMemory(true)); } static void MakeSomeGarbage() { Version vt; for(int i = 0; i < maxGarbage; i++) { // Create objects and release them to fill up memory // with unused objects. vt = new Version(); } }
Demo 2:
public class JhClient
WindowsFormsApplication1.exe 記憶體被限制在一定範圍之內,例如5104~5480之間