创建任务时列出索引超出范围异常 [英] List Index Out of Range exception when creating a task

查看:166
本文介绍了创建任务时列出索引超出范围异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确切的错误:

索引超出范围.必须为非负数并且小于集合的大小.

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

我已经索引了数组并列出了无数次.我已经使用数组循环并列出了无数次.数据在那里,它可以工作.除非我尝试为我的功能创建任务.提醒您,我成功地使用了foreach循环来实现了类似功能;这个新变量需要两个参数,因此我无法正确使用foreach循环.至少我认为我做不到.

I've index arrays and lists countless times. I've used for loops with arrays and lists countless times. The data is there, it works. Except when I try to create a task for my function. Mind you, I successfully did this with a foreach loop for a similar function; this new one requires two arguments though, so I can't use a foreach loop properly. At least I don't think I can.

这是错误的代码:

if (addressList != null) {
    textBox1.Text += ("Address List Length: " + addressList.Count + Environment.NewLine);

    for (int i = 0; i < addressList.Count; i++) {
        textBox1.Text += ("Task for " + addressList[i] + ":" + portList[i] + " initiated." + Environment.NewLine);

        Task.Factory.StartNew(() => PingTaskAdapted(addressList[i], portList[i]));
    }                
}
else textBox1.Text = ("No IPs have been added.");

假设addressList[0]是google.com,portList[0]是80, 输出:

Assuming addressList[0] is google.com and portList[0] is 80, Output:

Address List Length: 1
Task for google.com:80 initiated.

然后程序中断,Visual Studio告诉我,在PingTaskAdapted()处,我正在调用超出范围的索引,因为它实际上只是打印有问题的索引,因为它们存在.

then program break, with Visual Studio telling me that at PingTaskAdapted() I'm calling an index that is out of range, when it literally just printed the indexes in question, because they exist.

请注意,如果我打电话给PingTaskAdapted(addressList[0], pingList[0]);,它没有任何问题.

And just to be clear, if I call PingTaskAdapted(addressList[0], pingList[0]); it works with no issues.

推荐答案

任务运行时,您的任务将访问该列表.在循环中查看的代码行中没有顺序显示.为了确保在闭包中捕获了正确的值(并且列表仍然存在并且具有相同的值),请在任务外部创建本地副本,以确保在循环运行的那个时间点捕获了这些值:

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));

这篇关于创建任务时列出索引超出范围异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆