For loop goes out of range

后端 未结 3 611
滥情空心
滥情空心 2020-12-16 12:29
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        sta         


        
3条回答
  •  伪装坚强ぢ
    2020-12-16 13:08

    The reason is that you are using a loop variable inside a parallel task. Because tasks can execute concurrently the value of the loop variable may be different to the value it had when you started the task.

    You started the task inside the loop. By the time the task comes to querying the loop variable the loop has ended becuase the variable i is now beyond the stop point.

    That is:

    • i = 2 and the loop exits.
    • The task uses variable i (which is now 2)

    You should use Parallel.For to perform a loop body in parallel. Here is an example of how to use Parallel.For

    Alternativly, if you want to maintain you current strucuture, you can make a copy of i into a loop local variable and the loop local copy will maintain its value into the parallel task.

    e.g.

    for (int i = 0; i < 2; i++)
    {
      int localIndex = i;
      Task.Factory.StartNew(() => WorkerMethod(arr[localIndex])); 
    } 
    

提交回复
热议问题