I am trying to use TPL inside a while loop, and I need to pass the task some values, which then change into a loop. For example, here is an example with an index that increments (required after the line in which the task is requested to be created):
int index = 0; Task[] tasks; while(/*condition*/) { tasks[index] = Task.Factory.StartNew(() => DoJob(index)); index++; }
But, of course, this will not work, since the index value can be increased before the task starts. A possible solution could also be WaitHandle, on which wait until the index increases and which should be passed to the DoJob method, but this does not seem to me to be a really good solution. Any other idea?
Mauro ganswer
source share