0

I am learning Tasks and async method. But why some how the threads are faster than tasks in my examples. Looks like the async method are not running concurrently and but my threads are definitely are running concurrently.

Here is the code for the Tasks.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ConsoleApplication25
{
    using System.Diagnostics;
    using System.Threading;

    class Program
    {
        static void Main(string[] args)
        {
            var watch = Stopwatch.StartNew();
            watch.Start();
            Task.Run(
                async () =>
                    {
                        var ts = new CancellationTokenSource();
                        CancellationToken ct = ts.Token;

                        List<Task> myTasks = new List<Task>();

                        try
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                myTasks.Add(Print(i, ts));
                            }

                           await Task.WhenAll(myTasks);
                           // Task.WaitAll(myTasks.ToArray());
                        }
                        catch (OperationCanceledException ex1)
                        {
                            Console.Write("here" + ex1);
                        }
                        catch (Exception ex2)
                        {
                            Console.Write("bye" + ex2);
                        }


                    }).GetAwaiter().GetResult();


            watch.Stop();
            Console.WriteLine("total tasks = " + watch.ElapsedMilliseconds );


            var watch2 = Stopwatch.StartNew();
            watch2.Start();

            List<Thread> ThreadList = new List<Thread>();
            for (int i = 0; i < 10; i++)
            {
                Thread newThread = new Thread(ThreadPrint);
                ThreadList.Add(newThread);
                newThread.Start(i);
            }

            foreach (var mythread in ThreadList)
            {
                mythread.Join();
            }

            watch2.Stop();
            Console.WriteLine("total thread= " + watch2.ElapsedMilliseconds);
        }

        public static async Task Print(int id, CancellationTokenSource ts)
        {
            var watch = Stopwatch.StartNew();
            watch.Start();

            int counter = 0;

            while (true)
            {
                counter ++;
             //   Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "Loop " + id + ":::::" + "count = " + counter + "last =" + watch.ElapsedMilliseconds);
                if (counter == 200000000)
                {

                    watch.Stop();
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "EXIT " + id + ":::::" + "count = " + counter + "last =" + watch.ElapsedMilliseconds);
                    break;

                }
             //   Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "here it is " + id + ":::::" + "count = " + counter);
            }
        }

        public static void ThreadPrint(object id)
        {

            var watch = Stopwatch.StartNew();
            watch.Start();

            int counter = 0;

            while (true)
            {
                //Thread.Sleep(100);
                counter++;
                //   Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "Loop " + id + ":::::" + "count = " + counter + "last =" + watch.ElapsedMilliseconds);
                if (counter == 200000000)
                {

                    watch.Stop();
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "EXIT " + (int)id + ":::::" + "count = " + counter + "last =" + watch.ElapsedMilliseconds);
                    break;
                }
                //   Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "here it is " + id + ":::::" + "count = " + counter);
            }
        }
    }
}
retide
  • 1,170
  • 1
  • 13
  • 31

1 Answers1

1

Your code is incorrect

Your Print method is actually synchronous.

So in case of tasks, you create single Task and run your Print calls sequentially.

Correct way would be wrapping call to each Print instead of whole loop.

myTasks.Add(Task.Run(()=>Print(i, ts));
Oleh Nechytailo
  • 2,155
  • 17
  • 26
  • that is making my very confusing, when should I use task.run, when i dont have to do it? – retide Apr 14 '17 at 20:09
  • async method is not running concurrently? – retide Apr 14 '17 at 20:10
  • Thanks very much. I did some research and found out This link explained very well. http://stackoverflow.com/questions/17119075/do-you-have-to-put-task-run-in-a-method-to-make-it-async – retide Apr 14 '17 at 20:22