开发者

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

开发者 https://www.devze.com 2023-02-19 19:06 出处:网络
This question already has answers here: 开发者_如何转开发 Captured variable in a loop in C# (10 answers)
This question already has answers here: 开发者_如何转开发 Captured variable in a loop in C# (10 answers) Closed 2 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号