开发者

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜