Problem with adding a state to Task
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?'
开发者_Python百科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 finishing Main()
.
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);
}
精彩评论