6

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

Here is the error:

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.

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

2
  • your iterating variable may be updating inside the mResizeImage2 method Commented Aug 7, 2014 at 4:34
  • no, it is not updating anywhere else! Commented Aug 7, 2014 at 14:34

1 Answer 1

8

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, an explanation would also be great!
could you please explain how this is solving the issue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.