简体   繁体   English

如何在 .NET Core 中正确处理异步方法

[英]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.从C#开始 7.1 main方法可以声明为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:您可以像下面的示例一样使用 async/await 来捕获从 .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.您的代码的问题在于您正在等待Task成功执行,而这可能永远不会发生。 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.或者,您可以使用接受超时的Wait重载。 This is actually better because the completion of the task will be observed immediately, and not with a random 0-500 msec delay.这实际上更好,因为将立即观察到任务的完成,而不是随机的 0-500 毫秒延迟。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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