C#,为什么 GC 每秒运行几次?

标签 c# .net garbage-collection

<分区>

我正在开发一个创建交互式图表的程序。但是,即使禁用了程序的渲染层,也会出现以下问题。

在我的应用程序的某些屏幕上,根据 Visual Studio 2015 诊断工具,GC 每秒大约来回运行 4 次,从而降低了我的应用程序的性能(从 120fps 到低至 15fps)。

我拍摄了一些内存快照,希望看到意外的分配,但根据快照,每隔几秒只有一两次分配和收集 System.Internal.HandleCollector+HandleType,这似乎是正常的,即使问题是'发生。

我注意到的其他一些事情:

  • 这发生在多台机器上。
  • 无论是否附加调试器,都会发生这种情况。
  • 应用程序的大部分 CPU 时间都在 clr.dll 中。
  • 每次 GC 运行的原因被列为“Small object heap allocation”,即使快照中没有可观察到的分配。

此时我被难住了。有没有人见过这种情况或知道我应该从哪里开始调试?

最佳答案

来自 https://msdn.microsoft.com/en-us/library/ee787088(v=vs.110).aspx

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.

也许您正在满足上面列出的三个条件之一。您的应用程序似乎正在使用大量内存,因此垃圾收集正在运行以尝试清理一些对象以释放一些内存。

GC.Collect() 也可能在您的代码中某处,导致垃圾收集器再次运行。

Here是一些与垃圾回收相关的故障排除指南。其中一节似乎与您遇到的问题有关。在标记为“问题:垃圾收集期间的 CPU 使用率过高”的部分下,它说:

CPU usage will be high during a garbage collection. If a significant amount of process time is spent in a garbage collection, the number of collections is too frequent or the collection is lasting too long. An increased allocation rate of objects on the managed heap causes garbage collection to occur more frequently. Decreasing the allocation rate reduces the frequency of garbage collections.

You can monitor allocation rates by using the Allocated Bytes/second performance counter. For more information, see Performance Counters in the .NET Framework.

The duration of a collection is primarily a factor of the number of objects that survive after allocation. The garbage collector must go through a large amount of memory if many objects remain to be collected. The work to compact the survivors is time-consuming. To determine how many objects were handled during a collection, set a breakpoint in the debugger at the end of a garbage collection for a specified generation.

关于C#,为什么 GC 每秒运行几次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36556819/

相关文章:

c# - 我可以依靠 OSVERSIONINFO.szCSDVersion 或 Environment.OSVersion.ServicePack 始终采用 "Service Pack X"形式吗?

c# - 如何编写此嵌套的 Linq To Xml 查询

c# - "return"C#的返回类型是什么

c# - Parallel.Foreach 循环,与显式 throw 语句的行为不一致

c# - 检查是否已在 SqlDataReader 上调用 read()

c# - 如何让 Json.NET 将空 XML 元素序列化为空字符串

c# - 删除 TableLayoutPanel 中的行会导致布局问题

objective-c 内存管理--对象保证存在多长时间?

java - -Xmx属性与可用系统内存关联

heroku 上的 node.js Web 服务器 - 不断增长的内存