有没有一种方法可以检测GC集合何时运行? [英] Is there a way to detect when a GC collection has ran?

查看:63
本文介绍了有没有一种方法可以检测GC集合何时运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶BCL中没有通用的Pool类.我已经编写了自己的并且当前有关清空池的策略(即,没有从池中删除任何对象,因此它应该释放未使用的对象)基于计时器. 我不喜欢这个事实,但这是我能想到的最好的.我在想,理想情况下,我可以让我的池类基于GC收集的频率来制定其释放策略.最好的情况是在收集之前注册一个事件 会发生,然后它可能释放池中已有一段时间的对象.我能理解为什么.Net没有该事件,因为有人可能真的搞乱了GC的收集能力.因此,接下来最好的事情是 池类可以注册在每次GC收集结束时发生的事件.这样,池就可以跟踪我的GC收集对象如何生存,并且如果它超过了经过充分研究的限制,它可以释放对该对象的引用.

I'm rather surprised that there isn't a generic Pool class in the BCL. I've written my own and currently the policy around emptying pool (ie, no objects are being removed from the pool so it should release objects which aren't being used) is based on a timer. I don't like that fact, but it's the best I could come up with. I was thinking that ideally I could have my pool class base its releasing policy around the frequency of GC collections. The best situation would be registering for an event right before a collect would occur and then it could release objects which have been in the pool for a while. I can understand why .Net doesn't have that event because someone could really mess up the GC's ability to collect, ever. So the next best thing would be an event that the pool class could register to which happens at the end of every GC collect. That way the pool could keep track of how my GC collections an object has survived and if it gets past a well studied out limit, it could release the reference to that object.

由于GC类没有任何事件,会有其他方法吗?

Since the GC class doesn't have any events, would there be another way to do this?

推荐答案

一个IoC容器为您做到这一点.我知道Unity在内部工作中像这样工作,但主要的是...您不应该这样做. GC是设计无法预测的.

You could use an IoC container to do this for you. I know Unity works like this deep down it's inner working, but the main thing is... you shouldn't. The GC is unpredictable by design.

亲切的问候,
汤姆·德·科宁(Tom de Koning)

Kind regards,
Tom de Koning


这篇关于有没有一种方法可以检测GC集合何时运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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