开发者

What influences the timing of a GC?

I know it is not possible to know when a GC occurs, but there are fac开发者_Python百科tors that will tell you how often/when it may occur. What factors are these? One is how many objects are created, etc.


The short answer is that the following events trigger a collection cycle:

Allocation exceeds Gen0 threshold

Collection for a specific generation occurs when the memory threshold for that generation is hit. In the implementation of .NET Version 1.0, the initial thresholds for generations 0, 1, and 2 are 256 kilobytes (KB), 2 megabytes (MB), and 10 MB, respectively. Note that the GC can adjust these thresholds dynamically based on an application's patterns of allocation. Objects larger than 85 KB are automatically placed in the large object heap.

System.GC.Collect() is called

Allocations only happen in Gen0. After each GC, Gen0 is empty. New allocations will fill up Gen0 and the next GC will happen, and so on. The problem with calling GC.Collect() manually, is that you can end up with it being called more often than you predicted (due to the CLR calling it as well) and performance goes down because you are triggering GC cycles ahead of their schedule.

System is in a low memory situation

This is affected by other processes on the system which means you really have no control over it other than ensuring that you clean up resources correctly in your processes and components.


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 means that a threshold of acceptable memory usage has been exceeded on the managed heap. 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.


For the desktop version of C# there are a few factors:

  • Amount of memory allocation (Every time 1 MB is allocated a GC level 1 is triggered)
  • System memory pressure (if the amount of physical memory gets low, GC may be triggered)
  • Virtual Memory commits (if the system want's to commit memory pages, then a GC may be triggered prior to the operation)
  • Programmatic triggering from code.
  • Other heuristics may be used by GC to trigger collections.

In case you're interested when level 3 collections are about to happen in .Net framework 3.0 and above there are GC notifications that you can subscribe to, to be notified before they happen: RegisterForFullGCNotification

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜