-1

I'm running a series of tasks getting an integer as parameter, but the output is not as expected

static void Main(string[] args) {
 var tasks = new List < Task > ();

 for (int i = 0; i < 20; i++) {
  tasks.Add(new Task(async () => await MeuIp(i)));
 }

 Parallel.ForEach(tasks, task => {
  task.Start();
 });

 Console.ReadKey();
}

static async Task MeuIp(int i) {
 var r = await request.Ip();

 Console.WriteLine(i + " " + r);
}

Expected

0 ...
1 ...
2 ...
3 ...
4 ...
5 ...

Actual Output

Output

D Stanley
  • 149,601
  • 11
  • 178
  • 240

1 Answers1

1

Becase when a lambda function uses an outter scope variable it uses it's updated version, more correctly, the value that it will hold at the moment of the method call (i = 20 in that case) it is simply treated as an outter scope variable , the reason is that you are not acctually calling a method when you sent i as an argument you are just "preparing one" only at the call you are acctually using the variables.

You can simply introduct a variable and the issue will resolve:

for (int i = 0; i < 20; i++) {
    int k = i;
   tasks.Add(new Task(async () => await MeuIp(k)));
 }
Dr.Haimovitz
  • 1,568
  • 12
  • 16