Kugel
Kugel

Reputation: 19864

Can you explain this System.Collections.Generic.KeyNotFoundException?

I have following code:

mCommandMap[command.pId] = new System.Threading.ManualResetEvent(false);
SendCommandASync(command);
mCommandMap[command.pId].WaitOne();

Where mCommandMap is a Dictionary<string, ManualResetEvent> and pId is a string that is always created from GUID.NewGuid().ToString()

Now I'm in the debugger on the line that threw KeyNotFoundException. The debugger tells me there is one item in the dictionary and it has a key that is exactly the same the one I'm asking for. Go Figure.

Also this happens sporadically. Not always.

The question is, WTF?

Upvotes: 1

Views: 717

Answers (1)

František Žiačik
František Žiačik

Reputation: 7614

I guess you manipulate the command in multiple threads and its pId eventually changes.

Or, you manipulate mCommandMap in multiple threads without locking.

Try adding lock() arround the code.

Upvotes: 3

Related Questions