C# 垃圾回收?

C# Garbage collection?

我现在正在编写一个服务来自动化我的几个例程。现在我真的只是在上个月左右才开始学习 C#,所以我还是个新手(但到目前为止我真的很喜欢它)。我设计了我的服务,它只在我通过 AppSettings 制作的 5 分钟计时器上运行一个方法,运行一些检查,并在需要时组织一些事情,直到下一个间隔。

我很快意识到我做事的最初方式似乎有一个非常糟糕的内存泄漏。所以我重写了其中的大部分内容以将内容嵌入 "using" 块中,然后在完成后处理这些内容。 "using" 块是一位工作中的开发人员向我推荐的,他真的很有帮助,但我不想在他有工作要做时用我的个人项目打扰他。

目前我真的没有内存使用问题,因为它只使用了大约 25Mb 的内存,但是当它启动时,它只使用了大约 8Mb,并且它爬升的每个轮询间隔。但是一旦它达到 25Mb 的阈值,我可以看到是否下降一点,我假设是垃圾收集在做事情,然后它回升到 25Mb,然后冲洗并重复。所以我的应用程序内存使用量是稳定的,但它似乎比需要的要高,所以我很好奇。

现在,如果我手动调用 GC.Collect,内存使用量会减半。我意识到这并不理想,因为我已经对此进行了一些研究。但现在我的问题真正归结为,在内存使用和垃圾回收方面,.NET 中是否存在某种默认阈值?我问是因为它可以解释我所看到的。

我确实查看了 Process.MaxWorkingSet Property 上的此页面,但我不确定它是否会有所不同,或者只是可能给我带来问题。

我也尝试过 运行 一个分析器,但老实说,这对我来说仍然是新的,我并不完全清楚我在寻找什么。

Conditions for a garbage collection

Garbage collection occurs when one of the following conditions is true:

The system has low physical memory.

> The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.

The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.

> When the garbage collector detects that the survival rate is high in a generation, it increases the threshold of allocations for that generation, so the next collection gets a substantial size of reclaimed memory. The CLR continually balances two priorities: not letting an application's working set get too big and not letting the garbage collection take too much time.

引用自 msdn GC article