C#的HttpClient(块异步调用)僵局 [英] C# httpClient (block for async call) deadlock

查看:1666
本文介绍了C#的HttpClient(块异步调用)僵局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现状

有是不通过HttpClient.GetAsync一个GET请求的客户端。不幸的是,由于某些原因,我们需要在调用方框

There is a client that does a get-request by HttpClient.GetAsync. Unfortunately, for some reason, we need to block on that calls.

为了做到这一点,这Asynchelper类是为了避免上下文开关死锁(而不是只使用。结果)

In order to do so, this Asynchelper class is used in order to avoid context-switch deadlocks (instead of just using .Result)

   public static class AsyncHelper
   {
       private static readonly TaskFactory _myTaskFactory = new
             TaskFactory(CancellationToken.None,
                         TaskCreationOptions.None,
                         TaskContinuationOptions.None,
                         TaskScheduler.Default);


    public static void RunSync(Func<Task> func)
    {
        AsyncHelper._myTaskFactory
          .StartNew<Task>(func)
          .Unwrap()
          .GetAwaiter()
          .GetResult();
    }
}

然后实际调用看起来是这样的:

Then the actual call looks like this:

AsyncHelper.RunSync(Async Function() Await _httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead))

问题

在使用过程中Netlimiter降低网络速度的压力测试中,我们遇到了一个问题与未完成的请求。
例如,当我杀的网络连接(在NetLimiter),这样的请求将永远留在客户端上。
它会留在AsyncHelper.RunSync呼叫,直到它跑入httpClient.Timeout。

During a stress test using Netlimiter to reduce the network speed, we encountered a problem with requests that did not finish. For example, when I kill a network connection (in NetLimiter), such a request will stay forever on client side. It will stay in the AsyncHelper.RunSync-call until it runs into the httpClient.Timeout.

不应该有异常时的连接丢失,将结束通话?我缺少的东西吗?

Shouldn't there be an exception that will end this call when the connection is lost? Am I missing something?

推荐答案

的事情是,HTTP连接通常是骑在一个TCP连接。所以,当你被迫终止,没有它能够发送一个TCP连接,其我所做的一切,(或FIN)数据包,连接的另一端仍乐于等待更多的数据,至少要等到一些定义超时它可以从上面被配置在插座查询操作

The thing is that HTTP connections are usually riding over a TCP connection. So when you forcefully terminate a TCP connection without its being able to send its "I'm done here," (or FIN) packets, the other end of the connection is still happy to wait for more data, at least until some defined timeout which can be configured from above in socket-query operations.

要处理的一种方法是设置的 TCP保持活动的上的插座。请注意,这是非常不同的 HTTP 的保持活动。另一种选择是,因为似乎已经出现,使用的足够好的超时值。

One way to handle this is to set TCP Keep-Alive on the sockets. Note that this is very different from HTTP Keep-Alive. The other option is, as already seems to happen, to use a good-enough timeout.

这篇关于C#的HttpClient(块异步调用)僵局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆