我在c#中有一个多线程应用程序,它基本上使用lock()来访问字典。有2个线程,一个消费者和一个生产者。锁定机制非常简单。这个应用程序在重载下运行数周没有问题。
今天它刚刚崩溃。我深入了解WinDbg以查看Exception,并且在访问Dictionary时它是一个KeyNotFound。
可能导致此次崩溃的问题是什么?我是否应该考虑最终可能发生内存损坏?
答案 0 :(得分:9)
使锁定太细粒度可能会导致这种情况。例如:
bool hasKey(string key) {
lock (_locker) {
return _dictionary.ContainsKey(key);
}
}
int getValue(string key) {
lock (_locker) {
return _dictionary[key];
}
}
然后像这样使用它:
void Kaboom() {
if (hasKey("foo")) {
int value = getValue("foo");
// etc..
}
}
这不起作用,字典可以在hasKey和getValue调用之间切换。整个操作需要锁定。是的,这个问题每个月都会出错。
bool tryGetValue(string key, out int value) {
lock (_locker) {
if (!hasKey(key)) return false;
value = getValue(key);
return true;
}
}
答案 1 :(得分:0)
我们在使用
时注意到CMS框架代码中存在各种问题dictionary.ContainsKey ...相反,我们更改了代码以使用try..catch块,令人惊讶的是,它修复了我们的问题...请尝试将您的功能更改为:
int getValue(string key) {
lock (_locker) {
try {
return _dictionary[key];
} catch {
return null // or "" or whatever would fit....
}
}
}
看看它是否有帮助......