任务启动期间的变量更改 [英] Variable changes during Task Start

查看:70
本文介绍了任务启动期间的变量更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am really confused. I run the following code to execute two task, which work on separate folders, thats why I give them index. Unfortunately, when I run the code below, index passed to ProcessingTask static method is always 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
                );
        }

有什么想法吗?

推荐答案

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

You should place i into a temporary variable and use that, i.e.

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

请参见 查看全文

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