0

I have:

async void getData()
{
    Console.WriteLine("Start");
    HttpClient api = new HttpClient();
    await api.PostAsync("http://....",  someContent).ContinueWith(
         ....
    );
    Console.WriteLine("End");
}

void main()
{
    Task task = new Task(getData);
    task.Start();
    task.Wait();
    Console.WriteLine("Returned");
}

I consistently get the following output:

Start
Returned
End

How is it possible that the end of the getData method is executed after control has returned to the calling method?

Old Geezer
  • 14,854
  • 31
  • 111
  • 198

1 Answers1

3

Change

async void getData()

to

async Task getData()

The only place you should be using async void is for event handlers like button click in a WPF app. The reason not to use it is because you need to return something that can be awaited and returning void effectively negates that.

Also there is no need to create a new Task. You could rewrite this as follows:

void main()
{
    Task task = getData();
    task.Wait();
    Console.WriteLine("Returned");
}
Igor
  • 60,821
  • 10
  • 100
  • 175
  • Might want to explain what `async void` is doing here – BradleyDotNET Jul 27 '17 at 17:40
  • Still won't work right, because he is doing a `new Task(getData)` he needs to call `.Unwrap().Wait()` or use Task.Run – Scott Chamberlain Jul 27 '17 at 17:41
  • 2
    Just dont use async void. nuff said. Unless events.. – Botonomous Jul 27 '17 at 17:41
  • @ScottChamberlain - I was still editing / add to my answer :) (*typing as your comment appeared*), I had omitted the `Unwrap()` but added it now. Thanks. – Igor Jul 27 '17 at 17:45
  • *The only place you should be using async void is for WPF/WinForm event handlers* what about ASP.NET event handlers? does they not qualify? – Rahul Jul 27 '17 at 17:46
  • @Rahul - I updated my answer to make it more generic. I thought it was safe to return `Task` from an asp.net event handler though, maybe I am wrong. – Igor Jul 27 '17 at 17:50
  • @OldGeezer - see the code sample I added above for the `Main` method. That in combination with the changed signature should produce the desired result. – Igor Jul 27 '17 at 17:55
  • @Igor, when I used your method of starting the task, it hung after `api.PostAsync` completes. `End` and `Returned` are not printed. – Old Geezer Jul 27 '17 at 18:00
  • it's actually for any event handlers .. need not be necessarily for WPF only – Rahul Jul 27 '17 at 18:16