1

So I'm trying to create n Tasks and run them, but I'm not sure what I'm doing wrong

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

When running this I'm getting next(Also I don't get why it's task 5, i max number is 4):enter image description here

But if I'm creating Tasks manually like this

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

Everything is running as intendedenter image description here

What am I doing wrong?

HoTTab1CH
  • 199
  • 3
  • 20

1 Answers1

0

Making copy of loop variable helped, thx.

        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);
HoTTab1CH
  • 199
  • 3
  • 20