字典何时在Add或ContainsKey上抛出IndexOutOfRangeException? [英] When does a dictionary throw an IndexOutOfRangeException on Add or ContainsKey?
问题描述
在高负载,字典有时会进入一个状态,当我调用ContainsKey或Add方法时,它总是会抛出一个IndexOutOfRangeException。在私人FindEntry方法中发生异常。
我怀疑这可能是由于同步问题,但我不确定。
任何人都可以告诉我哪种情况可能发生?我的目标是收集足够的信息,以便我可以在开发环境中重现这个问题。
词典说明:
任何实例成员都不能保证线程安全。 / p>
要允许多个线程访问集合以进行阅读和写入,您必须实现自己的同步。
如果您不同步访问 Dictionary
,那么您可能会遇到类似于您所描述的问题(可能是因为内部状态不再有效)。如果您想在开发环境中尝试重现,请尝试创建一个程序,该程序使用多个线程从 Dictionary
不间断地读取和写入,而不进行同步。
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.
The documentation for Dictionary states:
Any instance members are not guaranteed to be thread safe.
To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
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 a Dictionary
without synchronization.
这篇关于字典何时在Add或ContainsKey上抛出IndexOutOfRangeException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!