我试图测试下面的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);
- }
- }