多线程应用程序崩溃 - 可能的内存损坏?

Mar*_*cus 0 c# memory locking memory-corruption

我在c#中有一个多线程应用程序,它基本上使用lock()来访问字典.有2个线程,一个消费者和一个生产者.锁定机制非常简单.此应用程序在重负载下运行数周而没有问题.

今天它刚刚崩溃.我深入了解WinDbg以查看Exception,并且在访问Dictionary时它是一个KeyNotFound.

哪些问题可能导致这次崩溃?我是否应该考虑最终可能发生内存损坏?

Han*_*ant 9

使锁定太细粒度可能会导致这种情况.例如:

    bool hasKey(string key) {
        lock (_locker) {
            return _dictionary.ContainsKey(key);
        }
    }
    int getValue(string key) {
        lock (_locker) {
            return _dictionary[key];
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

    void Kaboom() {
        if (hasKey("foo")) {
            int value = getValue("foo");
            // etc..
        }
    }
Run Code Online (Sandbox Code Playgroud)

这不起作用,字典可以在hasKey和getValue调用之间切换.整个操作需要锁定.是的,一个月左右就出错了.

    bool tryGetValue(string key, out int value) {
        lock (_locker) {
            if (!hasKey(key)) return false;
            value = getValue(key);
            return true;
        }
    }
Run Code Online (Sandbox Code Playgroud)