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

不羁的心 提交于 2020-07-15 07:08:41

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/5444673/starting-tasks-inside-a-loop-how-to-pass-values-that-can-be-changed-inside-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!