字典何时在 Add 或 ContainsKey 上引发 IndexOutOfRangeException?

When does a dictionary throw an IndexOutOfRangeException on Add or ContainsKey?(字典何时在 Add 或 ContainsKey 上引发 IndexOutOfRangeException?)

本文介绍了字典何时在 Add 或 ContainsKey 上引发 IndexOutOfRangeException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个繁忙的 ASP .NET 网站上,我有一个字典,它充当缓存,基本上存储键/值对以供以后检索.

On a busy ASP .NET website, I have a Dictionary, which acts as a cache, basically storing key/value pairs for later retrieval.

在高负载时,字典有时会进入一种状态,每当我调用 ContainsKey 或 Add 方法时,它总是抛出 IndexOutOfRangeException.异常发生在私有 FindEntry 方法中.

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.

推荐答案

字典 状态:

字典可以同时支持多个阅读器,只要不修改集合....要允许集合被多个线程访问以进行读写,您必须实现自己的同步.

A Dictionary<TKey,TValue> can support multiple readers concurrently, as long as the collection is not modified. ... To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

如果您没有同步访问 Dictionary,那么您可能会遇到您所描述的问题(可能是因为内部状态不再有效).如果您想尝试在您的开发环境中重现这一点,请尝试创建一个程序,该程序使用多个线程在不同步的情况下从 Dictionary 连续读取和写入.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:字典何时在 Add 或 ContainsKey 上引发 IndexOutOfRangeException?

基础教程推荐