List Index Out of Range exception when creating a task

后端 未结 3 2075
没有蜡笔的小新
没有蜡笔的小新 2020-12-20 11:53

The exact error:

Index was out of range. Must be non-negative and less than the size of the collection.

I\'ve index arrays and l

3条回答
  •  一整个雨季
    2020-12-20 12:38

    Closures capture variables, not values.

    Change the code to the following, and you'll see the issue go away:

    for (int i = 0; i < addressList.Count; i++) {
        textBox1.Text += ("Task for " + addressList[i] + ":" + portList[i] + " initiated." + Environment.NewLine);
    
        var temp = i;
        Task.Factory.StartNew(() => PingTaskAdapted(addressList[temp], portList[temp]));
        }                
    

提交回复
热议问题