在C#的for循环中启动并行异步任务:索引超出范围问题

问题描述

我有一个for循环,可在Main中并行并异步运行多个任务。我正在使用Task.Run()传递同步方法。我不想使“ DoStuff”方法异步。

tasks[i] = Task.Run(() => workers[i].DoStuff());

但是,我收到一个错误“ System.IndexOutOfRangeException:索引超出了数组的范围”。由于代码处理异步调用(并且内部可能处理多个线程),因此由于某些内部线程调度,循环变量“ i”可能会不一致地增加。共享变量的线程的典型问题。我知道Task与线程不同。如果我按步骤(F10)手动运行循环,则不会发生该错误。

您认为这是怎么回事?如何解决而不使方法“ DoStuff”异步?我知道如何使用List 来做同样的事情,但是我有兴趣了解使用数组时这里发生了什么以及是否有可能解决问题。

要测试的完整代码是:

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Issues01
{

    class Program
    {


        static void Main(string[] args)
        {
            Random rnd = new Random();
            // Build/Register/ComeToExistence all the workers for the demo
            // Force to create not only the array but the ojects inside
            int L = 10;
            MyWorkerClass[] workers = new MyWorkerClass[L]
                .Select(w => new MyWorkerClass(rnd.Next(1,500)))
                .ToArray(); 


            // Start the activity on each worker
            Task[] tasks = new Task[L];
            for (int i = 0; i < L; i++)
            {
                tasks[i] = Task.Run(() => workers[i].DoStuff());
            }

            Task.WaitAll(tasks);
        }


    }

    class MyWorkerClass
    {
        private const int MinTime = 1000;
        private const int MaxTime = 10000;

        private int _id;

        public MyWorkerClass(int id)
        {
            _id = id;
        }

        public void DoStuff()
        {
            Random rnd = new Random();
            Thread.Sleep(rnd.Next(MinTime,MaxTime));
            Console.WriteLine($"Worker {_id} done!");
        }

    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...