(有时)词典中不存在给定的键 [英] (Sometimes) The given key was not present in the dictionary
问题描述
我正在使用下面的代码以list参数启动线程,但有时会引发异常:
I am using the code below to start threads with a list parameter but sometimes it throws an exception:
字典中不存在给定的键
The given key was not present in the dictionary
从此行:
Thread MoveThread = new Thread(() => MoveTask(ControllerDictionary[i]));
如何解决该错误?
完整代码:
var ControllerDictionary = ConfigFile.ControllerList.Select((c, i) => new { Controller = c, Index = i })
.GroupBy(x => x.Index % AppSettings.SimultaneousProcessNumber)
.Select((g, i) => new { GroupIndex = i, Group = g })
.ToDictionary(x => x.GroupIndex, x => x.Group.Select(xx => xx.Controller).ToList());
for (int i = 0; i < ControllerDictionary.Count; i++)
{
Thread MoveThread = new Thread(() => MoveTask(ControllerDictionary[i]));
MoveThread.Start();
foreach (var Controller in ControllerDictionary[i])
Logger.Write(string.Format("{0} is in move thread {1}.", Controller.Ip, (i + 1)),EventLogEntryType.Information, AppSettings.LogInfoMessages);
}
推荐答案
您正在捕获变量 i
,而不是其值.因此,当前您可能有多个线程使用相同的索引调用MoveTask
...,有时i
的值可能等于ControllerDictionary.Count
.
You're capturing the variable i
, rather than its value. So currently you could have several threads calling MoveTask
using the same index... and sometimes the value of i
could be equal to ControllerDictionary.Count
.
如果将i
的副本放入循环中的变量中,则可以解决此问题,因为在循环的每次迭代中都会获得一个单独的变量:
If you take a copy of i
into a variable within the loop, that fixes the problem as you'll get a separate variable on each iteration of the loop:
for (int i = 0; i < ControllerDictionary.Count; i++)
{
int index = i;
Thread MoveThread = new Thread(() => MoveTask(ControllerDictionary[index]));
...
}
甚至更好的是,从线程中完全提取ControllerDictionary
提取:
Or even better, extract the ControllerDictionary
fetch from the thread entirely:
for (int i = 0; i < ControllerDictionary.Count; i++)
{
var value = ControllerDictionary[i];
Thread MoveThread = new Thread(() => MoveTask(value));
...
}
此外,还不清楚为什么要使用字典.既然您知道键都在[0, count)
范围内,为什么不只使用数组呢?您可以将查询更改为:
Additionally, it's not really clear why you're using a dictionary at all. Given that you know the keys will all be in the range [0, count)
why don't you just use an array? You'd change your query to:
var controllerLists = ConfigFile.ControllerList
.Select((c, i) => new { Controller = c, Index = i })
.GroupBy(x => x.Index % AppSettings.SimultaneousProcessNumber)
.Select(g => g.Select(xx => xx.Controller).ToList())
.ToArray();
这篇关于(有时)词典中不存在给定的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!