Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this async method quit before writing to file?

I am trying to get my head around async/await and wrote the following console application to download page content of a given URL (based on the httpclient example from dotnetperls)

Nothing gets written to the file. What am I doing wrong here?

static void Main()
{
    AsyncExample();
}

static async void AsyncExample()
{
    Task<string> task = DownloadPageAsync();
    string result = await task;
    WriteToFile(result, someFileName);
}

static async Task<string> DownloadPageAsync()
{
    string page = "http://en.wikipedia.org/wiki/Asynchronous_I/O";
    string result = string.Empty;

    using(HttpClient client = new HttpClient())
    using(HttpResponseMessage response = await client.GetAsync(page))
    using(HttpContent content = response.Content)
    {
        result = await content.ReadAsStringAsync();
    }
    return result;
}
like image 667
Animesh Avatar asked Dec 15 '22 21:12

Animesh


1 Answers

It is because the application is terminated. You need to wait until the AsyncExample finished before letting the main finish it's code.

Currently, the Main method finishes before your task does, and therefore the application is terminated immediately, regardless of the tasks status.

To solve this, you need to wait until the AsyncExample finishes.

One way to do it is to use a continuation and then to wait on this continuation Task using the Task.Wait() method.

We use a continuation for handling errors. Reading the Result property from the original task will throw an exception on error (do that if you want the exception to be thrown here).

Though, if we didn't use the continuation, and we didn't read the Exception value or the Result from a faulted task, then on finalizing the Task, the application could be terminated. the trick with the continuation handle both of these scenarios.

static async Task AsyncExample()
{
    Task<string> task = DownloadPageAsync();
    string result = await task;
    WriteToFile(result, someFileName);
}

public static void Main(string[] args)
{
    var task = AsyncExample();

    task.Wait();
    // task.ContinueWith( t => { }).Wait();
}
like image 147
m1o2 Avatar answered Jan 03 '23 12:01

m1o2