c# - (Sometimes) The given key was not present in the dictionary -
i using code below start threads list parameter throws exception:
the given key not present in dictionary
from line:
thread movethread = new thread(() => movetask(controllerdictionary[i])); how can fix error?
full code:
var controllerdictionary = configfile.controllerlist.select((c, i) => new { controller = c, index = }) .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()); (int = 0; < controllerdictionary.count; i++) { thread movethread = new thread(() => movetask(controllerdictionary[i])); movethread.start(); foreach (var controller in controllerdictionary[i]) logger.write(string.format("{0} in move thread {1}.", controller.ip, (i + 1)),eventlogentrytype.information, appsettings.loginfomessages); }
you're capturing variable i, rather value. have several threads calling movetask using same index... , value of i equal controllerdictionary.count.
if take copy of i variable within loop, fixes problem you'll separate variable on each iteration of loop:
for (int = 0; < controllerdictionary.count; i++) { int index = i; thread movethread = new thread(() => movetask(controllerdictionary[index])); ... } or better, extract controllerdictionary fetch thread entirely:
for (int = 0; < controllerdictionary.count; i++) { var value = controllerdictionary[i]; thread movethread = new thread(() => movetask(value)); ... } additionally, it's not clear why you're using dictionary @ all. given know keys in range [0, count) why don't use array? you'd change query to:
var controllerlists = configfile.controllerlist .select((c, i) => new { controller = c, index = }) .groupby(x => x.index % appsettings.simultaneousprocessnumber) .select(g => g.select(xx => xx.controller).tolist()) .toarray();
Comments
Post a Comment