For loop goes out of range

后端 未结 3 614
滥情空心
滥情空心 2020-12-16 12:29
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        sta         


        
3条回答
  •  情话喂你
    2020-12-16 13:25

    You are closing over loop variable. When it's time for WorkerMethod to get called, i can have the value of two, not the value of 0 or 1.

    When you use closures it's important to understand that you are not using the value that the variable has at the moment, you use the variable itself. So if you create lambdas in loop like so:

    for(int i = 0; i < 2; i++) {
        actions[i] = () => { Console.WriteLine(i) };
    }
    

    and later execute the actions, they all will print "2", because that's what the value of i is at the moment.

    Introducing a local variable inside the loop will solve your problem:

    for (int i = 0; i < 2; i++)
    {
        int index = i;
        Task.Factory.StartNew(() => WorkerMethod(arr[index])); 
    }
    

    That's one more reason to try Resharper - it gives a lot of warnings that help you catch the bugs like this one early. "Closing over a loop variable" is amongst them

提交回复
热议问题