在循环内启动任务:如何传递可以在循环内更改的值? [英] Starting tasks inside a loop: how to pass values that can be changed inside the loop?

查看:50
本文介绍了在循环内启动任务:如何传递可以在循环内更改的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在while循环中使用TPL,我需要将一些值传递给任务,然后将其更改为循环.例如,这里显示了一个示例,其中索引增加了(必须在请求创建任务的行之后):

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++;
}

但是它当然不起作用,因为可以在任务开始之前增加索引值.一个可能的解决方案可能是还传递一个WaitHandle,在等待它之前要递增索引,并且必须在DoJob方法中用信号通知它,但是在我看来,这并不是一个很好的解决方案.还有其他想法吗?

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++;
}

这样,每个任务将拥有 index while 循环的迭代期间具有其值的自己的副本,在该循环中,对 StartNew 的调用>已完成.

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.

这篇关于在循环内启动任务:如何传递可以在循环内更改的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆