简体   繁体   English

C#垃圾收集收集

[英]C# Garbage Collection Collect

So I was playing around with the C# Garbage Collection and I noticed a really weird thing. 所以我在玩C#垃圾收集,发现了一件很奇怪的事情。

Random r = new Random();
byte inl = 0;
while(true)
{
    inl = (byte)r.Next(0, 255);
    Console.WriteLine(inl);
    GC.Collect(0, GCCollectionMode.Forced, false, false);
}

I had this code in the main loop. 我在主循环中有此代码。 Without the GC.Collect function, the program was running with about 10MB of RAM. 如果没有GC.Collect函数,则程序运行时的RAM大约为10MB。 But with the GC.Collect function, it is running with 6MB of RAM. 但是使用GC.Collect函数,它可以在6MB的RAM上运行。

And then my question comes, why didn't the GC automatically delete the variable after it has been written to the console? 然后我的问题来了,为什么GC在将变量写入控制台后没有自动删除该变量?

There are different ways to clean up unused memory in different languages / frameworks. 有不同的方法可以清除不同语言/框架中未使用的内存。

In C++ land you have (for example) reference counted smart pointers, which automatically call delete on their pointers when their count hits zero. 在C ++领域中,您有(例如)引用计数的智能指针,当它们的计数达到零时,它们会自动对其指针调用delete。 If that's the behavior you're expecting in the .NET world, you'll be disappointed! 如果这是您在.NET世界中所期望的行为,您将感到失望! :) :)

The .NET GC model is very different. .NET GC模型非常不同。 To save you from having to worry about manually managing your memory, the CLR takes care of tracking which references are in use, and cleans up memory as needed. 为了使您不必担心手动管理内存,CLR会跟踪正在使用的引用,并根据需要清理内存。 However, monitoring and checking which references are in use is a relatively expensive process. 但是,监视和检查正在使用哪些引用是相对昂贵的过程。 The garbage collector therefore does not run continuously. 因此,垃圾收集器不会连续运行。 It kicks in, for example, when there's memory pressure (and in other situations, but this is of course a simplification). 例如,在存在内存压力时(以及在其他情况下,但这当然是一种简化)。

The short answer is basically: Let the garbage collector do its job. 简短的答案基本上是:让垃圾收集器完成工作。 It's a very smart and highly optimized system, and you should rarely (if ever) have to manually trigger garbage collection yourself. 这是一个非常智能且高度优化的系统,您几乎不需要(如果有的话)自己手动触发垃圾收集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM