helloworld
helloworld

Reputation: 2311

Where does Task Execution go?

Based on following code, my expectation was that console would emit

But task doesn't runs. Only first line emits in console. Please suggest why?

static void Main(string[] args)
    {
        var task2 = SayHelloTask();
        var result = task2.Result;
        Console.WriteLine(result);
    }

 public static Task<string> SayHelloTask()
        {
            Thread.Sleep(2000);
            Console.WriteLine("SayHelloTaskCalled");
            return  new Task<string>(() => {
                Console.WriteLine("Task Executing");
                return "SayHelloAfterSleepTask";
            });

Upvotes: 2

Views: 101

Answers (1)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73482

Creating a new Task using its one of the constructors hands you back a "Cold Task". Meaning that the Task isn't started yet. Since you've never started the Task, you don't see the expected output.

You need to call Task.Start to start it. In order to return a "Hot Task"(Started Task), you need to use Task.Factory.StartNew or Task.Run.

Following should work:

public static Task<string> SayHelloTask()
{
    Thread.Sleep(2000);
    Console.WriteLine("SayHelloTaskCalled");
    return  Task.Run(() => {
        Console.WriteLine("Task Executing");
        return "SayHelloAfterSleepTask";
       });
}

If you prefer your Task to be the "Cold Task" itself, then modify your calling code as below.

static void Main(string[] args)
{
    var task2 = SayHelloTask();
    task2.Start();//<--Start a "Cold task"
    var result = task2.Result;
    Console.WriteLine(result);
}

Upvotes: 6

Related Questions