2

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

  • SayTaskHelloCalled
  • Task Executing
  • SayHelloAfterSleepTask

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";
            });
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
helloworld
  • 2,179
  • 3
  • 24
  • 39

1 Answers1

6

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);
}
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • Thanks.. What changes are needed if I wish to start cold-task from calling code.. Let's say for some reason I want the caller to decide when to start the engine :) – helloworld Jan 02 '16 at 08:12
  • @helloworld Updated my answer. Hope that helps. But I recommend not to use Cold Tasks for public methods. Because almost every .net framework method returns a Task is a Hot Task. Returning a Cold Task creates unnecessary confusion. – Sriram Sakthivel Jan 02 '16 at 08:17
  • Oh.. It had a Start().. Pretty Succinct :) Thanks a lot.. Just one additional query.. What specific difference is there in returning Task v/s async Task .. as Task is already background.. My original query is answered though.. thanks – helloworld Jan 02 '16 at 08:29
  • I answered it [here](http://stackoverflow.com/questions/25191512/async-await-return-task). In short, an async Task will generate a State Machine. Where as other doesn't. – Sriram Sakthivel Jan 02 '16 at 08:41