I am trying to understand tasks and parallelism in C#. I have the code below in console application. I was expecting the code after Sleep() method to run after 3 millisecond but the program exits.
Can anyone please provide insights to why it's not waiting for 3 milliseconds and complete the execution of the remaining code. How can I make remaining code get executed after 3 millisecond?
static void Main(string[] args) { Task task = new Task(() => { Console.WriteLine("Task on thread {0} started.", Thread.CurrentThread.ManagedThreadId); Thread.Sleep(3000); Console.WriteLine("Task on thread {0} finished.", Thread.CurrentThread.ManagedThreadId); }); task.Start(); Console.WriteLine("this is the main thread"); }
Sleep
is measured in milliseconds.Sleep(3000)
will sleep for 3 seconds, not 3ms. You are dispatching your background work to a thread pool thread (which is a "Background thread" and will not keep your app alive). The way your program works is you start your app, dispatch work to a thread pool thread. It starts, but then stops for 3 seconds. Meanwhile, the foreground thread continues on and quits, ending the execution of your app before the Sleep ends.Task
constructor is frowned upon by the experts, unless you are doing something advanced that requires it. The common way of starting delegate-based tasks is by using theTask.Run
method.