c# – 异步后调试器在visual studio中调用HttpClient.GetAsync()
发布时间:2020-12-15 03:55:18 所属栏目:百科 来源:网络整理
导读:我试图测试下面的http请求方法 public async TaskHttpContent Get(string url) { using (HttpClient client = new HttpClient())// breakpoint using (HttpResponseMessage response = await client.GetAsync(url))// can't reach anything below this point
我试图测试下面的http请求方法
public async Task<HttpContent> Get(string url) { using (HttpClient client = new HttpClient()) // breakpoint using (HttpResponseMessage response = await client.GetAsync(url)) // can't reach anything below this point using (HttpContent content = response.Content) { return content; } } 但是,调试器似乎正在跳过第二个评论下面的代码.我正在使用Visual studio 2015 RC,有什么想法?我也尝试检查任务窗口,没有看到 编辑:找到解决方案 using System; using System.Net.Http; using System.Threading.Tasks; namespace ConsoleTests { class Program { static void Main(string[] args) { Program program = new Program(); var content = program.Get(@"http://www.google.com"); Console.WriteLine("Program finished"); } public async Task<HttpContent> Get(string url) { using (HttpClient client = new HttpClient()) using (HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false)) using (HttpContent content = response.Content) { return content; } } } } 原来,因为这是一个C#控制台应用程序,它在主线程结束之后结束,我猜是因为在添加一个Console.ReadLine()并等待一下后,请求确实返回.我猜C#会等到我的任务执行,而不是在它之前结束,但我想我错了.如果有人可以详细说明为什么会发生这样的事情会很好. 解决方法
当主出口时,程序退出.任何未完成的异步操作将被取消,并将其结果丢弃
因此,您需要阻止Main退出,无论是通过阻止异步操作或其他一些方法(例如,调用Console.ReadKey来阻止用户命中一个键): static void Main(string[] args) { Program program = new Program(); var content = program.Get(@"http://www.google.com").Wait(); Console.WriteLine("Program finished"); } 一种常见的方法是定义一个执行异常处理的MainAsync: static void Main(string[] args) { MainAsync().Wait(); } static async Task MainAsync() { try { Program program = new Program(); var content = await program.Get(@"http://www.google.com"); Console.WriteLine("Program finished"); } catch (Exception ex) { Console.WriteLine(ex); } } 请注意,阻塞异步代码通常被认为是一个坏主意;应该做的很少的情况,控制台应用程序的Main方法恰好恰好是其中之一. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |