How do I create a bunch of tasks in a loop

I have a list of 100 values

I want to spawn 5 threads to process 20 each

my code is basically

for (int i = 0; i<5; i++)
{

   Task.Run(() => {
       myMethod(myList.Skip(i * 20).Take(20)));
   });
}

Obviously because this closes over the value of i, it can totally screw it up. I've tried everything I can think of to get it to capture the value at the time the task is declared but I am having no luck at all. Even setting the first line of the Task.Run to var localVariable = i; to capture it does not work, it runs the method and i is 5 every time.

How do I do this, presumably I want to create the task by passing in the value of i so it never looks outside the function but I can't figure out how to do this.

Any ideas?

Jon Skeet
people
quotationmark

You're nearly there, but as well as creating a copy of the local variable, you need to use it in your lambda expression:

for (int i = 0; i < 5; i++)
{
   int localCopy = i;
   Task.Run(() => {
       myMethod(myList.Skip(localCopy * 20).Take(20)));
   });
}

If that doesn't work, then the problem isn't the variable capture - it's elsewhere.

Of course, another option is to use Parallel.ForEach with a custom partitioner, or something like that. In other words, there may well be better ways of approaching the problem.

people

See more on this question at Stackoverflow