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

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

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 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.
Oh.. It had a Start().. Pretty Succinct :) Thanks a lot.. Just one additional query.. What specific difference is there in returning Task<T> v/s async Task<T> .. as Task is already background.. My original query is answered though.. thanks
I answered it here. In short, an async Task will generate a State Machine. Where as other doesn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.