The given key was not present in the dictionary exception

I have a websocket server writen in C#. When I'm handling a packet from client in the server I get the error:

The given key ´4´ was not present in the dictionary.

This key exist. Other keys don't have this problem. The code pass the if statement.

string rawdata = Encoding.UTF8.GetString(decoded);
string[] msgdata = rawdata.Split("--");

int funcId = int.Parse(msgdata[0]);

if (Server.packetHandlersWS.ContainsKey(funcId)) {
    Server.packetHandlersWS[funcId](id, msgdata);
}

I tried cleanup on my project, I've tried deleting the .pdb files in the project and rebuilding. None of this fixes the problem.

Upvotes: -1

Views: 5627

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064184

Because packetHandlersWS is Dictionary<,> (from comments), there's a very good chance that you've corrupted the internal state, because you aren't doing any synchronization - and Dictionary<,> is not thread-safe. If this is the case, there's a very real chance that switching to ConcurrentDictionary<,> will fix this (note: you should still use TryGetValue with ConcurrentDictionary<,>, to avoid another race condition).

Upvotes: 1

Related Questions