c# - 添加到通用字典会导致 IndexOutOfRangeException

标签 c# .net concurrency race-condition

我在一些任务中使用字典。

从逻辑上讲,我已将其设置为我的键永远不会发生冲突,但有时在我向字典添加内容时会出现此异常。

Index was outside the bounds of the array.
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at Rpc.<MapIntoRpc>b__4[T](Object x) in Rpc.cs:line 113
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)
   at System.Threading.Tasks.Task.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()

我知道多次尝试删除或添加相同的 key 可能会出现并发问题,但我已经从算法上解决了这个问题。

是什么原因导致添加有时会失败? 解决这个问题的最佳方法是什么?

最佳答案

您应该查看文档。这就是它所说的:

A Dictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization. For a thread-safe alternative, see ConcurrentDictionary.

关于c# - 添加到通用字典会导致 IndexOutOfRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15095817/

相关文章:

c# - 如何在不同的核心上拆分长任务?

c# - 检查字符串是否存在于C#中的字符串列表中

c# - 如何以编程方式播放 16 位 PCM 数组

.net - 通过 URI 将用户名和密码传递给 .NET HttpWebRequest 不起作用

c++ - 在并发环境中访问 MMIO 的软件模式

sql - SELECT或INSERT函数是否容易出现竞争状况?

c# - 如何着手为 1 箱推箱子实现快速最短路径搜索?

c# - 如何实现RazorViewEngine FindView缓存

c# - 什么会使 PerformanceCounterCategory.Exists 无限期挂起?

multithreading - 测试高并发工作线程系统的正确方法是什么?