有限制的并发词典 [英] ConcurrentDictionary with limit

查看:74
本文介绍了有限制的并发词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些使用反射的代码.因此,我试图将反射的昂贵处理缓存到ConcurrentDictionary中.但是,我想对并发字典施加限制,以防止存储旧的和未使用的缓存值.

I'm writing some code that uses reflection. So I'm trying to cache the expensive processing of the reflection into a ConcurrentDictionary. However, I want to apply a restriction limit on the concurrent dictionary to prevent storing old and unused cached values.

我最后做了一些研究,以了解如何限制ConcurrentDictionary的大小.我找到了一些有趣的答案,但是我不知道答案是否符合我的要求,并且效果会很好.

I did some research on my end to see how to limit the size of the ConcurrentDictionary. I found some interesting answers, however I don't know if the answers suits my requirements and will perform well.

我在 Dapper 源代码中找到了他们做了一些自定义代码来处理ConcurrentDictionary的限制.它们具有与互锁一起使用的收集限制常量能够处理字典的并发.

I found in Dapper source code that they did some custom code to handle the limit of the ConcurrentDictionary. They have a collection limit constant that they use with Interlocked to be able to the handle the concurrency of the dictionary.

另一方面,我在SO上找到了答案,它使用普通的Dictionary,然后将其应用于ReaderWriterLockSlim处理并发.我不知道它是否与.Net源代码中的实现相同.

On the other hand, I found an answer on SO, that uses a normal Dictionary and then applies on it a ReaderWriterLockSlim to handle the concurrency. I don't know if it's the same implementation in .Net source code.

我应该使用dapper实施还是SO Answer实施?

Should I go with dapper implementation or the SO answer implementation?

推荐答案

在环境上进行缓存信息"的确切方法很多. WebDevelopment等领域需要完全不同的方法,这要归功于环境的大规模并行性和高度的分离性.

The exact way to go about "Caching Information" varries a lot on Environment. Areas like WebDevelopment need totally different approaches, thanks to the massively paralell nature of the environemt and high level of seperation.

但是缓存任何东西的核心是WeakReference.强引用会阻止GC进行收集. WeakReferences不会,但是可以让您获得强大的参考.这是程序员的一种说法:不要仅出于清单目的而将其保留在内存中.但是,如果您还没有收集它,请给我一个强有力的参考.":

But the core thing to do caching of anything is WeakReference. Strong References prevent the collection by the GC. WeakReferences do not, but allow you to get strong references. It is the programmers way of saying "Do not keep it in memory just for the sake of this list. But if you have not collected it yet, give me a strong reference please.":

https://msdn.microsoft.com/en-us /library/system.weakreference.aspx

从本质上讲,GC仅在所有其他线程都暂停时才可以收集(或标记该对象的弱引用).因此,WeakReferences不应使您面临其他竞争条件-它仍然存在并且您现在有很强的参考力,或者没有.

By it's nature, the GC can only collect (or tag weak references for that mater) when all other Threads are paused. So WeakReferences should not expose you to additional race conditions - it is either still there and you now have a strong reference, or it is not.

这篇关于有限制的并发词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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