【问题标题】:Trying to create n number of Tasks and run them in parallel. What am I doing wrong? [duplicate]尝试创建 n 个任务并并行运行它们。我究竟做错了什么? [复制]
【发布时间】:2019-03-23 11:01:38
【问题描述】:

所以我正在尝试创建 n 个任务并运行它们,但我不确定我做错了什么

class Program
{
    static void Main(string[] args)
    {
        int n = 5;
        Task[] taskList = new Task[n];
        for (int i = 0; i < n; i++)
        {
             taskList[i] = Task.Factory.StartNew(() => doStuff("Task" + i));
        }
        Task.WaitAll(taskList);

        Console.WriteLine("All threads complete");
        Console.ReadLine();


    }
    static void doStuff(string strName)
    {
        for (int i = 1; i <= 3; i++)
        {
            Console.WriteLine(strName + " " + i.ToString());
            Thread.Sleep(1000);
        }
    }
}

当运行这个时,我得到下一个(我也不明白为什么它是任务 5,我最大数量是 4):

但如果我像这样手动创建任务

        Task task1 = Task.Factory.StartNew(() => doStuff("Task1"));
        Task task2 = Task.Factory.StartNew(() => doStuff("Task2"));
        Task task3 = Task.Factory.StartNew(() => doStuff("Task3"));
        Task.WaitAll(task1, task2, task3);

一切都按预期运行

我做错了什么?

【问题讨论】:

  • @harold thx,当我在循环内复制变量时,它现在可以工作了,我很震惊我之前没有遇到过这个问题,谢谢。
  • 您是否考虑过使用 Microsoft 的 Reactive Framework (Rx) 来处理这类事情?

标签: c# .net multithreading task


【解决方案1】:

复制循环变量很有帮助,谢谢。

        int n = 5;
        Task[] taskList = new Task[n];
        for (int i = 0; i < n; i++)
        {
            int copy = i; //this helped
            taskList[i] = Task.Factory.StartNew(() => doStuff("Task" + copy.ToString()));
        }
        Task.WaitAll(taskList);

【讨论】:

    猜你喜欢
    • 2020-04-14
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 2016-07-18
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多