gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:11:53 25 4
gpt4 key购买 nike

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

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com