简体   繁体   中英

How to handle async methods properly in .NET Core

I am looking to retrieve a website response and send dots to the screen whilst doing so.

I am unable to do so using the code below. I'm sure I'm doing something rather silly, looking for any insights..

Console.Write("Doing Task...");
HttpClient web = new HttpClient();
Task<HttpResponseMessage> resp = web.GetAsync("http://localhost",
    HttpCompletionOption.ResponseContentRead);
resp.RunSynchronously(); //Doesn't Work
resp.Start(); //Doesn't Work
while (resp.Status != TaskStatus.RanToCompletion)
{
    Write.Operation(".");
    Thread.Sleep(500);
}
Console.Write("Done!");

Why don't you use async/await? Starting from C# 7.1 main method can be declared as async.

using System;
using System.Net.Http;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main()
    {
        Console.WriteLine("Doing Task...");
        using HttpClient client = new HttpClient();
        var resp = await client.GetAsync("http://localhost");
        var content = await resp.Content.ReadAsStringAsync();
        Console.WriteLine("Done!");
    }
}

you can use async/await like the example below to capture any data returned from server in .NET Core:

static async Task Main(string[] args)
{
  using var httpClient = new HttpClient();
  var result = await client.GetAsync("http://localhost");
  Console.WriteLine(result.StatusCode);
}

The problem with your code is that you are waiting for the successful execution of the Task , and this may never happen. You need to wait for its completion instead, whether successful or unsuccessful:

Console.Write("Doing Task...");
HttpClient httpClient = new HttpClient();
var task = httpClient.GetAsync("http://localhost");
while (!task.IsCompleted)
{
    Console.Write(".");
    Thread.Sleep(500);
}
task.Wait(); // observe any exceptions that may have occured
Console.WriteLine("Done!");

Alternatively you could use the Wait overload that accepts a timeout. This is actually better because the completion of the task will be observed immediately, and not with a random 0-500 msec delay.

while (!task.Wait(500))
{
    Console.Write(".");
}
Console.WriteLine("Done!");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM