简体   繁体   English

字典异常中不存在给定的键

[英]The given key was not present in the dictionary exception

I have a websocket server writed in c#C#.我有一个用 c#C# 编写的 websocket 服务器。 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 doesn't has this problem.其他键没有这个问题。 The code pass the if statement.代码传递 if 语句。

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 delet the.pdb files in the project and rebuild.我尝试清理我的项目,我尝试删除项目中的 .pdb 文件并重建。 None of this fixes the problem.这些都不能解决问题。

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.因为packetHandlersWSDictionary<,> (来自评论),所以您很有可能破坏了内部 state,因为您没有进行任何同步 - 而Dictionary<,>不是线程安全的。 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).如果是这种情况,切换到ConcurrentDictionary<,>很有可能会解决此问题(注意:您仍应将TryGetValueConcurrentDictionary<,>一起使用,以避免出现另一个竞争条件)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM