宰杀在WeakReferences在.NET集合最佳时间时间、WeakReferences、NET

2023-09-03 01:38:53 作者:ヤ嘽°咡鐶づ

我有一个集合(我正在写一个弱词典),我需要定期剔除死在WeakReferences。什么我通常看到的是,在添加检查和删除的方法说,在X修改的集合,它的时间来宰杀。这将是可以接受我,但似乎应该有一个更好的办法。

I have a collection (I'm writing a Weak Dictionary) and I need to cull the dead WeakReferences periodically. What I've usually seen is checks in the Add and Remove methods that say, "After X modifications to the collection, it's time to cull." This will be acceptable for me, but it seems like there should be a better way.

我真的很想知道,当GC运行和c后,立即跑我清理$ C $。毕竟,GC可能是决定何时是一个很好的时间来清理死引用的最佳机制。我发现垃圾收集通知,但它并不像这我想要的是。我不想产生一个单独的线程正好并监控GC上。理想情况下,我的收藏​​将实施 IWantToRun codeDuringGC 或订阅 System.GC.Collected 事件。但是,.NET框架恐怕不能相信用户code进行GC期间运行...

I would really like to know when the GC ran and run my cleanup code immediately after. After all, the GC is probably the best mechanism for determining when is a good time to clean up dead references. I found Garbage Collection Notifications, but it doesn't look like this is what I want. I don't want to spawn a separate thread just to monitor the GC. Ideally, my collection would implement IWantToRunCodeDuringGC or subscribe to a System.GC.Collected event. But the .NET framework probably can't trust user code to run during a GC...

或者,也许还有另一种方法我俯瞰。

Or maybe there's another approach I'm overlooking.

编辑:我不认为它很重要,如果我的code后运行,之前,或GC时

I don't think it matters if my code runs after, before, or during the GC.

推荐答案

我想你想创建一个弱的字典作为一些数据的懒缓存的方式。

I guess you want to create a weak dictionary as a way of "lazy" caching of some data.

您需要考虑的是,GC会经常发生,你的弱引用会死人的大部分时间,如果没有其他对象的引用它们。发生胃癌的每个内存256KB分配后约。这是pretty的频率。

You need to consider the fact that GC will occur very often and your weak references will be dead most of the time if no other objects will reference them. GC occurs approximately after every 256KB of memory is allocated. It is pretty often.

您可能会通过实施缓存作为一个与元素的最大数量的字典更好。然后你可以使用最近最少使用算法或基于时间的算法为推动元件出集合。通常这种方法比使用弱引用更好的性能和内存消耗。

You probably will be better by implementing your cache as a dictionary with a maximum number of elements. Then you can use least-recently used algorithm or time-based algorithm for pushing elements out of the collection. Usually such approach has better performance and memory consumption than using weak references.