C# 中的强制垃圾回收

Muhammad Maisam Abbas 2023年12月11日
C# 中的强制垃圾回收

本教程将讨论在 C# 中强制垃圾回收的方法。

在 C# 中使用 GC.Collect() 方法强制垃圾回收

C# 中的 GC.Collect() 方法执行强制垃圾收集。GC.Collect() 方法回收所有不可访问的内存。使用此方法,将考虑清理内存中的所有对象。但是,不考虑将托管代码段中引用的对象视为清理对象。

using System;

namespace randomize_array {
  class Program {
    static void Main(string[] args) {
      int[] i = new int[100000];
      GC.Collect();
    }
  }
}

在上面的代码中,我们首先使用 int[] i = new int[100000] 行在内存中生成了一些未使用的垃圾,然后用 C# 中的 GC.Collect() 方法强迫垃圾收集器收集垃圾并释放所有的内存。

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn