我有这个代码:
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/