Friday, 13 December 2019

So when does a Task start?

This question can turn out to be funny if you don't pay attention. So, i wrote an simple code so that it gives clarity to the uninitiated.

private static async Task WriteWithDelay()
{
            Console.WriteLine($"Write before delay in thread id : {Thread.CurrentThread.ManagedThreadId} at {DateTime.UtcNow.Ticks}");
            await Task.Delay(10000).ConfigureAwait(false);
            Console.WriteLine($"Write after delay in thread id : {Thread.CurrentThread.ManagedThreadId} at {DateTime.UtcNow.Ticks}");
            return Thread.CurrentThread.ManagedThreadId;

  }

 static async Task Main(string[] args)
 {
            Task[] tasks = new Task[10];
            for(int i = 0; i < tasks.Length; i++)
            {
                tasks[i] = WriteWithDelay();
            }

            Console.WriteLine($"Before when all at {DateTime.UtcNow.Ticks}");
            await Task.WhenAll(tasks);

            Console.WriteLine($"After when all at {DateTime.UtcNow.Ticks}");
}

Well, you can check the output and be clear about the order in which things happen.

Write before delay in thread id : 1 at 637118566941927002
Write before delay in thread id : 1 at 637118566942107032
Write before delay in thread id : 1 at 637118566942114110
Write before delay in thread id : 1 at 637118566942117029
Write before delay in thread id : 1 at 637118566942117029
Write before delay in thread id : 1 at 637118566942117029
Write before delay in thread id : 1 at 637118566942117029
Write before delay in thread id : 1 at 637118566942117029
Write before delay in thread id : 1 at 637118566942127007
Write before delay in thread id : 1 at 637118566942127007
Before when all at 637118566942127007
Write after delay in thread id : 4 at 637118567043690656
Write after delay in thread id : 11 at 637118567043690656
Write after delay in thread id : 5 at 637118567043690656
Write after delay in thread id : 7 at 637118567043690656
Write after delay in thread id : 13 at 637118567043690656
Write after delay in thread id : 9 at 637118567043690656
Write after delay in thread id : 12 at 637118567043690656
Write after delay in thread id : 8 at 637118567043690656
Write after delay in thread id : 6 at 637118567043690656
Write after delay in thread id : 10 at 637118567043700652
After when all at 637118567043871008

No comments:

Post a Comment