I have a multi-threaded application in c# which basically uses lock() to access a dictionary. There are 2 threads, a consumer and a producer. The locking mecanism is very simple. This application runs under heavy load for weeks without a problem.
Today it 开发者_Python百科just crashed. I digged into WinDbg to see the Exception and it was a KeyNotFound when accessing the Dictionary.
What problems could cause this crash? Should I consider that memory corruption eventually may occur or not?
Making the locking too fined-grained could cause this. For example:
bool hasKey(string key) {
lock (_locker) {
return _dictionary.ContainsKey(key);
}
}
int getValue(string key) {
lock (_locker) {
return _dictionary[key];
}
}
And then using it like this:
void Kaboom() {
if (hasKey("foo")) {
int value = getValue("foo");
// etc..
}
}
That won't work, the dictionary could change between the hasKey and the getValue call. The entire operation needs to be locked. And yes, this goes wrong once a month or so.
bool tryGetValue(string key, out int value) {
lock (_locker) {
if (!hasKey(key)) return false;
value = getValue(key);
return true;
}
}
We have noticed various problems in our CMS framework code while using
dictionary.ContainsKey... instead we changed the code to use a try..catch block and amazingly, it has fixed our issues... please also try to change your function to something like this:
int getValue(string key) {
lock (_locker) {
try {
return _dictionary[key];
} catch {
return null // or "" or whatever would fit....
}
}
}
see if it helps...
精彩评论