Sunday, 11 March 2018

c# Task.Run async await

//run task one by one in sequence

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            my_timer = Stopwatch.StartNew();

            work_sequence();
         
            Console.Read();
        }

        private static void Work(int n)
        {
            Console.WriteLine("working on thread " + n + " at "+my_timer.Elapsed);
            Thread.Sleep(1000);
            Console.WriteLine("done thread " + n + " at " + my_timer.Elapsed);
        }     

        private static Stopwatch my_timer { get; set; }

        private async static void work_sequence()
        {
            for(int i=0;i<5;i++)
            {
                await Task.Run(() => Work(i+1));
            }

        }
    }
}

----------------------------------------------------
working on thread 1 at 00:00:00.0348544
done thread 1 at 00:00:01.0371825
working on thread 2 at 00:00:01.0379072
done thread 2 at 00:00:02.0383723
working on thread 3 at 00:00:02.0388026
done thread 3 at 00:00:03.0392966
working on thread 4 at 00:00:03.0401340
done thread 4 at 00:00:04.0410059
working on thread 5 at 00:00:04.0414497
done thread 5 at 00:00:05.0418085

No comments:

Post a Comment