I just started learning how to use Task in C#. But I’ve encountered a problem in the very beginning. When I run this code , nothing gets displayed in Console window.Why?’
static void Main(string[] args)
{
Task task1 = new Task((obj) => PrintMsg(obj), "Hello Task");
task1.Start();
}
static void PrintMsg(object msg)
{
Console.WriteLine(msg);
}
Your program is exiting before the task (which runs in a background thread) can finish.
Add
task1.Wait();to wait for the task to finish running before finishingMain().