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?
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.
精彩评论