在循环内启动任务:如何传递可以在循环内更改的值?

发布于 2024-10-27 01:50:04 字数 368 浏览 1 评论 0原文

我正在尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一抹微笑 2024-11-03 01:50:04

将值分配给循环内的临时变量:

int index = 0;
Task[] tasks;
while(/*condition*/)
{
    int value = index;
    tasks[index] = Task.Factory.StartNew(() => DoJob(value));
    index++;
}

这样,每个任务都将拥有自己的 indexwhile 循环迭代期间所拥有的值副本,其中调用到 StartNew 已完成。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文