List Index Out of Range exception when creating a task

后端 未结 3 2074
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  -上瘾入骨i
    2020-12-20 12:40

    Your task will be accessing the list when the task runs. Not sequentially in the line of code you look at in the loop. To make sure that the correct values are captured in the closure (and the lists still exists and has the same values), make local copies outside of the task, that make sure the values are captured at that point in time the loop runs:

    var localAddress = addressList[i];
    var localPort = portList[i];
    Task.Factory.StartNew(() => PingTaskAdapted(localAddress , localPort));
    

提交回复
热议问题