本文介绍了在 Visual Studio 中调用异步 HttpClient.GetAsync() 后调试器停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试以下 http 请求方法

I'm trying to test the follwing http request method

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,有什么想法吗?我也尝试检查任务窗口,但什么也没看到

However, the debugger seems to be skipping the code below the 2nd comment. I'm using Visual studio 2015 RC, any ideas? I also tried checking the Tasks window and saw nothing

找到解决方案

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# 会等到我的任务执行而不是在它之前结束,但我想我错了.如果有人能详细说明发生这种情况的原因,那就太好了.

Turns out that because this was a C# console app it ended after the main thread ends I guess, because after adding a Console.ReadLine() and waiting a bit, the request did return. I guessed that C# would wait until my task execute and not end before it, but I suppose I was wrong. If anybody could elaborate on why this happened it would be nice.

推荐答案

Main 退出时,程序退出.取消所有未完成的异步操作并丢弃其结果.

When Main exits, the program exits. Any outstanding asynchronous operations are canceled and their results discarded.

因此,您需要阻止 Main 退出,通过阻止异步操作或其他一些方法(例如,调用 Console.ReadKey 阻止直到用户点击一个键):

So, you need to block Main from exiting, either by blocking on the asynchronous operation or some other method (e.g., calling Console.ReadKey to block until the user hits a key):

static void Main(string[] args)
{
  Program program = new Program();
  var content = program.Get(@"http://www.google.com").Wait();
  Console.WriteLine("Program finished");
}

一种常见的方法是定义一个 MainAsync 来处理异常:

One common approach is to define a MainAsync that does exception handling as well:

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 方法恰好是其中之一.

Note that blocking on asynchronous code is generally considered a bad idea; there are very few cases where it should be done, and a console application's Main method just happens to be one of them.

这篇关于在 Visual Studio 中调用异步 HttpClient.GetAsync() 后调试器停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 12:23