IndexOutOfRangeException when using tasks in a for loop in C #

I am trying to use tasks in a for loop, but I am getting a 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);

      

Here is the error:

An exception of type "System.IndexOutOfRangeException" occurred in mCPanel.exe but was not handled in user code Additional information: The index was outside the array.

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

+3


source to share


1 answer


try copying ii to local variable inside 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);

      



This is necessary because you are accessing the modified closure. For example, since Task.Run () won't run right away, and you just simply pass it to it (without copying it locally), the value of ii might change when the ThreadPool decides to run that particular task. See Modified Close Access for details

+3


source







All Articles