Miro
Miro

Reputation: 1806

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?'

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

Answers (2)

VMAtm
VMAtm

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

SLaks
SLaks

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

Related Questions