Why does this async method exit before writing to a file?

I try to get around async/awaitand wrote the following console application to load the page contents of a given URL (based on the example httpclient from dotnetperls)

Nothing is 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;
}
+4
source share
2 answers

This is because the application is complete. You need to wait until AsyncExample is finished before allowing the main one to complete the code.

Currently, the Main method ends before your task completes, and therefore the application immediately terminates, regardless of the state of the tasks.

, , AsyncExample.

: , Task.Wait().

. Result ( , , ).

, , Exception , . .

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();
}
+9

, m1o2:

, , Exception , .

  • , TPL. .NET 4.0 UnobservedTaskException . .NET 4.5 . . this blog post Stephan Toub

  • . await task , await "". , .

  • Task.Wait AggregationException, Task.Result Task.Exception. from MSDN:

, , , , , . Task.Wait Task<TResult>.Wait, try-catch.

+3

Source: https://habr.com/ru/post/1546492/


All Articles