gpt4 book ai didi

c# - (有时)词典中不存在给定的键

转载 作者:太空宇宙 更新时间:2023-11-03 17:42:18 25 4
gpt4 key购买 nike

我正在使用下面的代码以list参数启动线程,但有时会引发异常:

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

如果将i的副本复制到循环中的变量中,则会解决此问题,因为在循环的每次迭代中都会得到一个单独的变量:

for (int i = 0; i < ControllerDictionary.Count; i++)
{
int index = i;
Thread MoveThread = new Thread(() => MoveTask(ControllerDictionary[index]));
...
}

甚至更好的是,从线程中完全提取 ControllerDictionary提取:
for (int i = 0; i < ControllerDictionary.Count; i++)
{
var value = ControllerDictionary[i];
Thread MoveThread = new Thread(() => MoveTask(value));
...
}

此外,目前还不清楚为什么要使用字典。既然您知道键都在 [0, count)范围内,为什么不只使用数组呢?您可以将查询更改为:
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();

关于c# - (有时)词典中不存在给定的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16644738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com