Implement MultiThreading using Task class in C#

Last Reply 11 months ago By pandeyism

Posted 11 months ago

Hi,

I am calling a same function using loop via TASK, as mentioned below :

    class Program
    {
        static void Main(string[] args)
        {
            List<Task> MyTaskList = new List<Task>();

            for (int i = 0; i < 10; i++)
            {
                Program Obj = new Program();
                MyTaskList.Add(Task.Run(() => Console.WriteLine(i)));
            }

            Task.WhenAll(MyTaskList.ToArray());
            Console.Read();
        }

        public void PrintTask(int i)
        {        
            Console.WriteLine(i);
        }
    }

Expected Output :

1 2 3 4 5 till 10

Actual Output : 10 10 10 till 10 times.

Not sure why this function is not calling one by one.

Any help

Posted 11 months ago

Hi Amit,

Please refer below code.

Code

C#

List<Task> MyTaskList = new List<Task>();
for (int i = 0; i < 10; i++)
{
    var temp = i;
    MyTaskList.Add(Task.Factory.StartNew(() => Console.WriteLine(temp+1)));
}
Task.WaitAll(MyTaskList.ToArray());

Output

1 2 3 4 5 6 7 8 9 10