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 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:
And then using it like this:
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.