Reputation: 1806
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);
}
Upvotes: 3
Views: 978
Reputation: 28355
Add some code for wait the task:
static void Main(string[] args)
{
Task task1 = new Task((obj) => PrintMsg(obj), "Hello Task");
task1.Start();
// or Console.ReadLine();
task1.Wait();
}
static void PrintMsg(object msg)
{
Console.WriteLine(msg);
}
Upvotes: 3
Reputation: 887777
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 finishing Main()
.
Upvotes: 6