Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting tasks inside a loop: how to pass values that can be changed inside the loop? [duplicate]

I'm trying to use TPL inside a while loop and I need to pass to the task some values that then changes into the loop. For instance, here it is shown an example with an index that is incremented (necessarily after the line in which the task creation is requested):

int index = 0;
Task[] tasks;
while(/*condition*/)
{
    tasks[index] = Task.Factory.StartNew(() => DoJob(index));
    index++;
}

But of course it does not work, since the index value can be incremented before the task start. A possible solution could be to pass also a WaitHandle on which waiting before incrementing the index and that has to be signalled into the DoJob method, but it doesn't seem to me a really good solution. Any other idea?

like image 571
Mauro Ganswer Avatar asked Mar 26 '11 19:03

Mauro Ganswer


1 Answers

Assign the value to a temporary variable inside the loop:

int index = 0;
Task[] tasks;
while(/*condition*/)
{
    int value = index;
    tasks[index] = Task.Factory.StartNew(() => DoJob(value));
    index++;
}

That way each task will have its own copy of the value that index had during the iteration of the while loop in which call to StartNew was made.

like image 51
Fredrik Mörk Avatar answered Sep 24 '22 12:09

Fredrik Mörk