2

I'm trying to get my head around await and async so I wrote this little test app, but what I expected does not happen.

Instead of waiting for the task to complete, the program continues to execute.

class Program
{
    static void Main(string[] args)
    {
        var task = new Task(Run);
        task.Start();
        task.Wait();

        Console.WriteLine("Main finished");
        Console.ReadLine();
    }

    public async static void Run()
    {
        var task = Task.Factory.StartNew(() =>
        {
            Console.WriteLine("Starting");
            Thread.Sleep(1000);
            Console.WriteLine("End");
        });

        await task;
        Console.WriteLine("Run finished");
    }
}

Output

Main finished
Starting
End
Run finished

If I swap the 'await task' for 'task.Await()' it then runs as I would have expected producing

Starting
End
Run finished
Main finished
sQuir3l
  • 1,373
  • 7
  • 12
  • I hope this link will help you http://stackoverflow.com/a/9519578/2798643 – Govinda Rajbhar Nov 29 '14 at 12:20
  • I have an [async intro blog post](http://blog.stephencleary.com/2012/02/async-and-await.html) that you may find useful. Note that your code [should not use the task constructor](http://blog.stephencleary.com/2014/05/a-tour-of-task-part-1-constructors.html) [nor `Task.Factory.StartNew`](http://blog.stephencleary.com/2013/08/startnew-is-dangerous.html) (both links to my blog). – Stephen Cleary Nov 29 '14 at 12:30

1 Answers1

5

That is because when you have asynchronous void method, there is nothing you can do to track it's completion. Yours new Task(Run) only creates a task for starting the Run method. After the Run arrives at first await, there is nothing tracking the progress of the method, because there is nothing associated with the progress of the method. To fix it, you have to return Task instead of void and await that, instead of creating new Task.

Difference between async void and async Task is described here.

Euphoric
  • 12,645
  • 1
  • 30
  • 44