-1

I am running the following simplified code:

public static void runCode(int num){
  Console.WriteLine("Task {0}",num);
  for(int j=0;j<10;j++)
    Console.Write(num);
}

public static void Main(string[] args){
  // some operations here
  for(int i=0;i<numIterations;i++){
    Console.WriteLine("Current number={0}",i);
    Task.Run(()=>runCode(i));
  }
  // remaining code
}

The result is the following one:

Current number=0
Current number=1
Current number=2
Current number=3
Task 4
4444444444Task 4
4444444444Task 4
4444444444Task 4
4444444444

Why does the shown number is always the same? Maybe for static?

aegon
  • 11
  • 5
  • 1
    By the time `runCode(i)` runs on these other threads, your loop has already completed, and the value of i is 4. This is also a multiultidupe, but I can't be arsed to find the canonical. –  Jul 12 '17 at 15:10

1 Answers1

0

Here is the explanation of this behavior, and that's how you fix it:

public static void runCode(int num)
{
    Console.WriteLine("Task {0}", num);
    for (int j = 0; j < 10; j++)
        Console.Write(num);
}

public static void Main(string[] args)
{
    // some operations here
    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine("Current number={0}", i);
        var x = i;
        Task.Run(() => runCode(x));
    }
    // remaining code
}
  • Thank you very much! I've also tried a similar solution, but I placed the declaration of i1 OUTSIDE the for cycle, so the result was the same as before. Thank you! – aegon Jul 12 '17 at 15:14