任务启动期间的变量更改

时间:2013-05-10 15:09:34

标签: c# parallel-processing task

我真的很困惑。我运行以下代码来执行两个任务,它们在单独的文件夹上工作,这就是为什么我给它们索引。不幸的是,当我运行下面的代码时,传递给ProcessingTask静态方法的索引总是2 ...

        tasks = new Task[sets.ThreadCount];
        for (int i = 0; i < sets.ThreadCount; i++)
        {
            tasks[i] = Task.Factory.StartNew
                (
                 () =>
                 {
                     ProcessingTask.run(
                                         i,
                                         stack,
                                         collector,
                                         sets,
                                         cts.Token,
                                         LOG
                                        );
                 },
                 cts.Token,
                 TaskCreationOptions.LongRunning,
                 TaskScheduler.Default
                );
        }

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您应该将i放入临时变量并使用它,即

int iTemp = i;
tasks[i] = Task.Factory.StartNew(() => {
        ProcessingTask.run(
                             iTemp,
                             stack,
                             collector,
                             sets,
                             cts.Token,
                             LOG
                            );
     },
     cts.Token,
     TaskCreationOptions.LongRunning,
     TaskScheduler.Default
    );

请参阅http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx了解