并发字典的用途
您认为人们可以在哪里找到并发词典的用法,这是.Net框架4?
有人用过并发词典吗,如果用过的话为什么?如果有例子的话那就太好了。
我可以想到它在工厂模式中的用途,其中您想要存储类的不同实例(如果它已经初始化)。例如。 Hibernate 会话工厂。你怎么认为?
Where do you think one could find usages for the Concurrent Dictionary thats part of the .Net framework 4?
Has anybody used the Concurrent Dictionary, if so why? Examples if any would be great.
I can think of its uses in the factory pattern wherein you want to store different instances of a class if it has been initialized already. Eg. Hibernates SessionFactory. What do you think?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我在缓存场景中大量使用它。
ConcurrentDictionary
,尤其是与Lazy
结合使用时,非常适合 当类型的构造成本很高时缓存结果,并且在多线程场景中正常工作。I've used it heavily for caching scenarios.
ConcurrentDictionary
, especially when combined withLazy<T>
, is great for caching results when construction of a type is expensive, and works properly in multithreaded scenarios.每当我不想真正担心对字典的并发访问时 - 即我有一些小型 HTTP Web 服务器应用程序,它在字典结构中记录/缓存一些请求数据 - 可以有任意数量的并发请求,但我不这样做想要处理必须手动
锁定
字典的问题。这只是您不必自己做并且可能出错的另一件事,相反,框架会为您处理这方面的事情。
Whenever I don't want to worry about concurrent access to the dictionary really - i.e. I have some tiny HTTP web server app which logs/caches some request data in a dictionary structure - there can be any number of concurrent requests and I don't want to deal with having to manually
lock
the dictionary.It's just one more thing that you don't have to do yourself and potentially get wrong, instead the framework takes care of that aspect for you.
我们用它来缓存多线程应用程序中的对象...性能非常好,不用担心
lock
或类似的问题...We use it for caching objects in a multi-threaded app... performance is great and no worries about
lock
or similar...任何需要线程安全的基本缓存都是候选者,特别是对于本质上高度线程化的 Web 应用程序。字典需要锁;要么是独占的,要么是读者/作者(后者更难以编码)。哈希表对于读取者来说自动是线程安全的(需要写入者锁定),但通常涉及键(有时是值)的装箱,并且没有静态类型安全。
然而,并发字典使用起来确实很友好;没有锁代码,并且完全线程安全。比读/写锁(包括“slim”类型)开销更少。
Any basic cache that you need to be thread-safe is a candidate, especially for web apps that are inherently highly threaded. A dictionary requires a lock; either exclusive or reader/writer (the latter being more awkward to code). A hashtable is automatically thread-safe for readers (requiring a lock for writers), but often involves boxing of keys (and sometimes values), and has no static type safety.
A concurrent dictionary, however, is really friendly to use; no lock code, and entirely thread-safe. Less overhead than reader/writer locks (including the "slim" variety).