添加到通用字典会导致IndexOutOfRangeException [英] Adding to a generic dictionary causes IndexOutOfRangeException

查看:127
本文介绍了添加到通用字典会导致IndexOutOfRangeException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某些Task中使用字典。

I'm using a dictionary inside of some Task.

从逻辑上讲,我已经对其进行了设置,以使我的键永远不会发生冲突,尽管有时在我添加到字典中时会出现此异常。

Logically I have set it up so that my Keys will never clash, though sometimes when I am adding to the dictionary I get this Exception.

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可能会带来并发问题,但是我已经从算法上进行了解释。

I understand there can be concurrency issues from trying to remove or add the same Key multiple times, but I have accounted for that algorithmically.

是什么原因导致添加有时失败?
最好的解决方法是什么?

What causes the add to sometimes fail? What is the best way to work around that?

推荐答案

您应该已经阅读了文档。它说的是:

You should have looked to the documentation. That what it says:


只要不修改集合,字典可以同时支持多个阅读器。即使这样,通过集合枚举本质上也不是线程安全的过程。在极少数情况下枚举与写访问竞争的情况下,必须在整个枚举期间锁定集合。要允许多个线程访问该集合进行读写,您必须实现自己的同步。
有关线程安全的替代方法,请参见ConcurrentDictionary。

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.

这篇关于添加到通用字典会导致IndexOutOfRangeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆