GC.Collect() [英] GC.Collect()

查看:49
本文介绍了GC.Collect()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我已经阅读了一些关于它的主题,但它就在这里.让我们假设我有一个应用程序,基本上我会时不时地单击一个按钮,很多事情会发生几分钟,然后它可能会再闲置一个小时,或者可能只有 1 分钟.不是在整个结束之后调用 GC.Collect 的好情况吗?我的意思是,我确实知道在那一刻我不会使用我的应用程序,GC 无法猜测.

Ok, I've read a couple of topics about it, but here it goes. Let's imagine I have an application where basically every now and then I will click on a button, a lot of things will happen for a couple of minutes, and then it'll stay idle possible for another hour, or maybe just 1 minute. Wouldn't just after that whole ended a good situation to call GC.Collect? I mean, I do know that just at that moment I will not being using my application, and GC cannot guess it.

推荐答案

我可以看到有几个人在不建议调用 GC.Collect 方面表现得很极端.

I can see that several people have gone extreme about not recommending to call GC.Collect.

GC.Collect 的存在是有原因的,以下是我对何时以及为何调用 GC.Collect 的建议.

GC.Collect is there for a reason, here are my recommendation of when and why to call GC.Collect.

  1. 一般来说,不要担心调用它,GC 会很好地自我调整并且会做正确的事情.

  1. In General, don't worry about calling it, GC tunes itself very well and will do the right thing.

有时,您最终会遇到这样的情况:您确定这是调用它的正确时间,您上面描述的情况正是调用它的正确时间,实际上 Asp.Net 调用了 GC.在与您描述的情况相似的某些点收集.

Sometimes, you end up in situation where you know for sure that this is the right time to call it, the situation you described above is exactly the right time to call it, in fact Asp.Net calls GC.Collect at certain points that are similar to what you described.

GC 很聪明地调用 GC.Collect,如果你调用了 GC.Collect,GC 可以覆盖你的决定并且仍然不收集(你在调用 GC.Collect 时必须设置一个标志来选择此行为),这是调用 GC.Collect 的推荐方式,因为您仍在让 GC 决定是否是收集的好时机.

The GC is smart about calling GC.Collect, if you called GC.Collect, the GC can override your decision and still doesn't collect ( you have to set a flag when you call GC.Collect to choose this behavior), this is the recommended way of calling GC.Collect, since you are still letting the GC decides if it is a good time to collect.

不要接受我的建议是调用 GC.Collect 的一般性声明,您应该始终避免调用它,除非您确实确定需要调用它,像您描述的情况正是 GC 的原因.收集在那里.

Don't take my recommendation is a general statement for calling GC.Collect, you should always avoid calling it, unless you REALLY sure you need to call it, situation like the one you described is exactly why GC.Collect is there.

调用它的好处是可以快速释放垃圾,一般情况下你会关心这种情况

The benefit you will get from calling it is freeing the garbage quickly, generally you will care about this situation if

  1. 您处于内存不足的情况下,想要急于收集,如果您处于内存不足的情况下,GC 无论如何都会积极主动,如果机器上的内存压力很大,它会自动启动
  2. 如果您想避免陷入内存不足的情况,并且想急切地收集.

希望这会有所帮助.
谢谢

Hope this helps.
Thanks

这篇关于GC.Collect()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆