在循环内启动任务:如何传递可以在循环内更改的值?
我正在尝试在 while 循环内使用 TPL,并且需要将一些值传递给任务,然后这些值会更改为循环。例如,这里显示了一个索引递增的示例(必须在请求创建任务的行之后):
int index = 0;
Task[] tasks;
while(/*condition*/)
{
tasks[index] = Task.Factory.StartNew(() => DoJob(index));
index++;
}
但是它当然不起作用,因为索引值可以在任务开始之前递增。一个可能的解决方案可能是还传递一个 WaitHandle,在增加索引之前等待,并且必须将其发送到 DoJob 方法,但在我看来这并不是一个很好的解决方案。还有其他想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将值分配给循环内的临时变量:
这样,每个任务都将拥有自己的
index
在while
循环迭代期间所拥有的值副本,其中调用到StartNew
已完成。Assign the value to a temporary variable inside the loop:
That way each task will have its own copy of the value that
index
had during the iteration of thewhile
loop in which call toStartNew
was made.