I try to run several tasks at the same time, and I ran into a problem that I cannot understand and cannot solve.
I had a function like this:
private void async DoThings(int index, bool b) { await SomeAsynchronousTasks(); var item = items[index]; item.DoSomeProcessing(); if(b) AVolatileList[index] = item;
What I wanted to call in a for loop using Task.Run() . However, I could not find a way to send parameters to this Action<int, bool> , and everyone recommends using lambdas in such cases:
for(int index = 0; index < MAX; index++) { //let 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; } }
I thought that using local variables in lambdas would βcaptureβ their values, but it doesn't seem like that; it will always take the index value, as if the value were fixed at the end of the for loop. The index variable is evaluated at 400 in lambda at each iteration, so of course I get an IndexOutOfRangeException 400 times ( items.Count is actually MAX ).
I'm really not sure what is going on here (although it is very interesting to me), and I do not know how to do what I am trying to achieve. Any hints are welcome!
source share