To get the behavior you want you need to wait for the process to finish before you exit Main()
. To be able to tell when your process is done you need to return a Task
instead of a void
from your function, you should never return void
from a async
function unless you are working with events.
A re-written version of your program that works correctly would be
class Program { static void Main(string[] args) { Debug.WriteLine("Calling DoDownload"); var downloadTask = DoDownloadAsync(); Debug.WriteLine("DoDownload done"); downloadTask.Wait(); //Waits for the background task to complete before finishing. } private static async Task DoDownloadAsync() { WebClient w = new WebClient(); string txt = await w.DownloadStringTaskAsync("http://www.google.com/"); Debug.WriteLine(txt); } }
Because you can not await
in Main()
I had to do the Wait()
function instead. If this was a application that had a SynchronizationContext I would do await downloadTask;
instead and make the function this was being called from async
.