在C#中的for循环中使用任务时出现IndexOutOfRangeException异常 [英] IndexOutOfRangeException exception when using tasks in for loop in C#

查看:99
本文介绍了在C#中的for循环中使用任务时出现IndexOutOfRangeException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在for循环中使用任务,但是我遇到了非常奇怪的异常!这是我的代码:

I am trying to use tasks in a for loop, but I am getting really strange exception! here is my code:

        Task[] tasks = new Task[strarrFileList.Length];
        for (int ii = 0; ii < strarrFileList.Length; ii++)
        {
            tasks[ii] = Task.Factory.StartNew(() => mResizeImage2(ii, strarrFileList[ii], intLongSide, jgpEncoder, myEncoderParameters));
        }
        Task.WaitAll(tasks);

这是错误:

mCPanel.exe中发生了类型为'System.IndexOutOfRangeException'的异常,但未在用户代码中处理 附加信息:索引不在数组的范围内.

An exception of type 'System.IndexOutOfRangeException' occurred in mCPanel.exe but was not handled in user code Additional information: Index was outside the bounds of the array.

所以基本上ii等于strarrFileList.Length,这不应该!有人对此有解释/解决方案吗?

So basically ii becomes equal to strarrFileList.Length which shouldn't! Does anyone have an explanation/solution for this?

推荐答案

尝试将ii复制到for循环内的局部变量.

try copying ii to a local variable inside the for loop.

Task[] tasks = new Task[strarrFileList.Length];
for (int ii = 0; ii < strarrFileList.Length; ii++)
{
    var currentIndex = ii;
    tasks[currentIndex] = Task.Run(() => mResizeImage2(currentIndex, strarrFileList[currentIndex], intLongSide, jgpEncoder, myEncoderParameters));
}
Task.WaitAll(tasks);

这是必需的,因为您正在访问修改后的闭包.例如,由于Task.Run()不会立即运行,而您只是将ii传递给它(无需在本地复制它),因此当ThreadPool确实决定运行该特定Task时,ii的值可能会更改.有关更多信息,请参见访问修改后的闭包

This is needed because you are accessing a modified closure. For example, since Task.Run() will not run right away, and you are simply just passing ii to it (w/out copying it locally), the value of ii may change when the ThreadPool does decide to run that particular Task. More info, see Access to Modified Closure

这篇关于在C#中的for循环中使用任务时出现IndexOutOfRangeException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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