字典何时在 Add 或 ContainsKey 上抛出 IndexOutOfRangeException?
在一个繁忙的 ASP .NET 网站上,我有一个字典,它充当缓存,主要存储键/值对以供以后检索。
在高负载下,字典有时会进入一种状态,每当我调用 ContainsKey 或 Add 方法时,它总是抛出 IndexOutOfRangeException。异常发生在私有 FindEntry 方法内部。
我怀疑这可能是由于同步问题造成的,但我不确定。
谁能告诉我在什么情况下会发生这种情况?我的目标是收集足够的信息,以便我可以在开发环境中重现该问题。
On a busy ASP .NET website, I have a Dictionary, which acts as a cache, basically storing key/value pairs for later retrieval.
On high load, the Dictionary some times get into a state, where it always throws an IndexOutOfRangeException whenever i call the ContainsKey or Add method. The exception happens inside the private FindEntry method.
I am suspecting that this might be due to a synchronization issue, but I am not sure.
Can anyone tell me under which circumstances this can happen ? My goal is to gather enough information so that I can reproduce the issue in the dev environment.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
字典 指出:
如果您没有同步对
Dictionary
的访问,那么您可能会遇到您所描述的问题(可能是因为内部状态不再有效)。如果您想尝试在开发环境中重现此情况,请尝试创建一个程序,该程序使用多个线程在不同步的情况下连续从Dictionary
读取和写入。The documentation for Dictionary states:
If you are not synchronizing access to the
Dictionary
, then you might get issues like those you describe (presumably because the internal state is no longer valid). If you want to try and reproduce this in your development environment, then try creating a program that uses multiple threads to continuously read and write from aDictionary
without synchronization.我同意这几乎肯定是同步问题。
我不知道有任何文档准确描述了这种情况何时以及如何发生 - 如果您以非线程安全的方式使用字典,则该行为是未定义的。
为了在您的开发环境中进行测试,我建议运行一些并行线程,这些线程在连续循环中随机插入、删除、更新等(基本上是生产环境中发生的情况的“集中”版本)。
I agree that this is almost certainly a synchronisation issue.
I'm not aware of any documentation that describes exactly when and how this can happen - the behaviour is undefined if you use a dictionary in a non-threadsafe manner.
For testing in your dev environment, I'd suggest running some parallel threads that randomly insert, remove, update etc in a continuous loop (basically a "concentrated" version of what's happening in your production environment).
这是一个线程安全字典 http://devplanet.com/blogs/brianr/archive/2008/09/26/thread-safe-dictionary-in-net.aspx 还可以查看 这个问题。
Here's a thread-safe dictionary http://devplanet.com/blogs/brianr/archive/2008/09/26/thread-safe-dictionary-in-net.aspx also check out this SO question.