C# 字典索引超出带锁的数组范围

标签 c# multithreading dictionary locking

我有这个代码:

lock (dict)
{
    dict.Add(someKey, someValue);
    Task task = new Task (() => doSomething);
    task.Start();
    task.ContinueWith(() => {dict.Remove(someKey);});
}

既然我已经锁定了 dict,为什么我仍然收到错误

"Index was outside the bounds of the array"

我无法重现该错误,但另一个人重现了。

最佳答案

dict.Remove(someKey); 不在锁内部运行。它在不同的线程上运行。此代码未正确同步。

可能,您需要的是lock (dick) dict.Remove(someKey);。然后,字典就会正确运行。然而,添加删除 不会是一个原子操作。

关于C# 字典索引超出带锁的数组范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36646760/

相关文章:

C# List - 添加到列表底部

java - 将 ThreadLocal 类传递给另一个线程?

c++ - 多线程 (openMP) - 有多少并行线程

java - 我应该在使用 getOrDefault() 之后使用 put() 还是 putIfAbsent()?

c# - 如何防止将方法添加到类中?

c# - 如何对采用对象数组并在 ASP.Net MVC 中返回 JsonResult 的 Action 方法进行单元测试

c# - 为什么在实现 IEnumerator<T> 的类中需要 IEnumerator.Current?

c - 在 C 中线程化 : Producer Consumer taking forever to run

python - Python map(None, fcn()) 是否有更简单的构造?

python - 使用csv写两个字典