我正在尝试同时运行多个任务,但遇到了一个问题,我似乎无法理解或解决。
我曾经有这样一个函数:
private void async DoThings(int index, bool b) {
await SomeAsynchronousTasks();
var item = items[index];
item.DoSomeProcessing();
if(b)
AVolatileList[index] = item; //volatile or not, it does not work
else
AnotherVolatileList[index] = item;
}
我想在使用
Task.Run()
的for
循环中调用一个方法。然而,我找不到一种方法将参数发送给这个Action<int, bool>
,每个人都建议在类似情况下使用lambda表达式:for(int index = 0; index < MAX; index++) { //let's say that MAX equals 400
bool b = CheckSomething();
Task.Run(async () => {
await SomeAsynchronousTasks();
var item = items[index]; //here, index is always evaluated at 400
item.DoSomeProcessing();
if(b)
AVolatileList[index] = item; //volatile or not, it does not work
else
AnotherVolatileList[index] = item;
}
}
我曾认为在lambda中使用局部变量会"捕获"它们的值,但事实并非如此;它将始终采用索引的值,就好像该值将在
for
循环结束时被捕获一样。在每次迭代中,index
变量在lambda中被评估为400,因此我会得到400次IndexOutOfRangeException
(items.Count
实际上是MAX
)。我真的不确定这里发生了什么(虽然我真的很好奇),也不知道如何实现我想要的东西。任何提示都欢迎!