开发者

Multi-threaded application crash - possible memory corruption?

开发者 https://www.devze.com 2023-02-12 12:59 出处:网络
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

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...

0

精彩评论

暂无评论...
验证码 换一张
取 消