NeatNerd
NeatNerd

Reputation: 2373

Variable changes during Task Start

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

Any ideas?

Upvotes: 0

Views: 202

Answers (1)

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
    );

see http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx for explanation

Upvotes: 2

Related Questions