I have below code:
class Program
{
static void Main(string[] args)
{
Task[] tasks = new Task[3]
{
Task.Factory.StartNew(() => Console.WriteLine("Hello A")),
Task.Factory.StartNew(() => Console.WriteLine("Hello B")),
Task.Factory.StartNew(() => Console.WriteLine("Hello C"))
};
Task.WaitAll(tasks);
Console.WriteLine("Hi ABC");
}
}
I build and run the above code, it gives output:
Hello C
Hello B
Hello A
Hi ABC
But if I comment Task.WaitAll(tasks), one of the outputs is:
Hi ABC
Hello B
Hello C
Does it mean when Console.WriteLine(“Hi ABC”) finishes execution, thread which executes Console.WriteLine(“Hello A”) didn’t get a chance to finish execution?
Yes, that’s correct. Your main thread is terminating the process before the child threads have finished – or started in some cases. If you don’t do something to keep the main thread busy, then when the main thread terminates (after “Hi ABC”), the process termination will kill all outstanding threads. If the A thread (or any of the child threads) hasn’t been scheduled yet, then it won’t have a chance to output at all.