调试器在visual studio中调用异步HttpClient.GetAsync()后停止

时间:2015-07-07 23:23:38

标签: c# asynchronous async-await visual-studio-2015

我试图测试以下的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#会等到我的任务执行而不是在它之前结束,但我想我错了。如果有人能详细说明为什么会这样,那就太好了。

0 个答案:

没有答案