IndexOutOfRangeException exception when using tasks in for loop in C#

前端 未结 1 1185
感情败类
感情败类 2021-01-03 10:41

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


        
相关标签:
1条回答
  • 2021-01-03 11:15

    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

    0 讨论(0)
提交回复
热议问题