这个问题该怎么解决,请赐教
- C# code
Dictionary<string, byte[]> deviceDic=new Dictionary<string, byte[]>() ;byte[] pcPacketData = new byte[700];byte[] pcPacketData1 = new byte[700];byte[] pcPacketData2 = new byte[700];////数组赋值省略//deviceDic.Add("0", pcPacketData);deviceDic.Add("1", pcPacketData1);deviceDic.Add("2", pcPacketData2);Dictionary<string, byte[]> tempDic = new Dictionary<string, byte[]>();tempDic = deviceDic;foreach (string key in tempDic.Keys){ if(key!=2) { lock(deviceDic) { deviceDic.Remove(key); } } }
这是一个线程里面要做的,另外一个线程给deviceDic加元素,现在的问题是foreach那老是弹出集合已修改,可能无法执行枚举操作,我已经又new了一个tempDic了,为什么tempDic也跟着deviceDic变啊。
[解决办法]
- C# code
Dictionary<string, byte[]> deviceDic = new Dictionary<string, byte[]>();byte[] pcPacketData = new byte[700];byte[] pcPacketData1 = new byte[700];byte[] pcPacketData2 = new byte[700];deviceDic.Add("0", pcPacketData);deviceDic.Add("1", pcPacketData1);deviceDic.Add("2", pcPacketData2);Dictionary<string, byte[]> tempDic = new Dictionary<string, byte[]>();lock (deviceDic){ foreach (string key in deviceDic.Keys) { if (key != "2") { tempDic.Add(key, deviceDic[key]);// 将要处理的键值存入 tempDic 临时变量 } } foreach (var item in tempDic.Keys) { deviceDic.Remove(item); }}// 处理 tempDic 中的数据