Garbage collection in C# not carried out. Why?

后端 未结 5 2000
感动是毒
感动是毒 2021-02-12 03:58

I have tried a simple experiment to verify the functionality of the garbage collector. Referencing 3.9 Automatic memory management (MSDN) about automatic memory managem

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-12 04:16

    The .NET garbage collector is an highly optimized, complicated beast of software. It is optimized to make your program run as fast as possible and using not too much memory in doing so.

    Because the process of freeing memory takes some time, the garbage collector often waits to run it until your program uses a whole lot of memory. Then it does all the work at once, which results in a small delay of your program after a relatively long time (instead of many smaller delays earlier, which would slow down your program).

    All this means, that the time the garbage collector runs is not predictable.

    You may call your test several times (with some Sleep() in the loop) and watch memory usage slowly building up. When your program begins to consume a significant portion of available physical memory its memory usage will suddenly drop to near-zero.

    There are a couple of functions (like GC.Collect()) which force several levels of garbage collection, but it's strongly advised not to use them unless you know what you are doing, because this tends to make your software slower and stops the garbage collector in doing its work in an optimal way.

提交回复
热议问题