[英]How to handle async methods properly in .NET Core
我正在寻找检索网站响应并在这样做时将点发送到屏幕。
我无法使用下面的代码这样做。 我确定我正在做一些相当愚蠢的事情,寻找任何见解......
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!");
你为什么不使用异步/等待? 从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!");
}
}
您可以像下面的示例一样使用 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);
}
您的代码的问题在于您正在等待Task
的成功执行,而这可能永远不会发生。 您需要等待它完成,无论是成功还是不成功:
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!");
或者,您可以使用接受超时的Wait
重载。 这实际上更好,因为将立即观察到任务的完成,而不是随机的 0-500 毫秒延迟。
while (!task.Wait(500))
{
Console.Write(".");
}
Console.WriteLine("Done!");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.