[英]Why is first HttpClient.PostAsync call extremely slow in my C# winforms app?
I have an httpclient like this:我有一个这样的 httpclient:
var client = new HttpClient();
I post to it like this:我这样发帖:
var result = client.PostAsync(
endpointUri,
requestContent);
And get the response like this:并得到这样的回应:
HttpResponseMessage response = result.Result;
I understand this call will block the thread, thats how its supposed to work (just building a tool for myself, no async threads needed)我知道这个调用会阻塞线程,这就是它应该如何工作的(只是为我自己构建一个工具,不需要异步线程)
The first time I run this call, it takes about 2 minutes to get a result.我第一次运行此调用时,大约需要 2 分钟才能得到结果。 Meanwhile, if I do the exact same call elsewhere its done in 200ms.
同时,如果我在其他地方进行完全相同的调用,它会在 200 毫秒内完成。 Even if I hit google, it takes 2 minutes.
即使我打谷歌,也需要2分钟。 But, after the first call, as long as I keep the app open any additional calls are good.
但是,在第一次通话后,只要我让应用程序保持打开状态,任何其他通话都没有问题。 Its just the first cal when I open the application.
当我打开应用程序时,它只是第一次校准。 What could be causing this?
是什么原因造成的?
The problem was that it was hanging for a very long time trying to resolve a proxy for the client.问题是它在尝试为客户端解析代理时挂起很长时间。 Initializing the HttpClient like this did the trick:
像这样初始化 HttpClient 就成功了:
var client = new HttpClient(new HttpClientHandler
{
UseProxy = false
});
In my case I was trying to access a service on localhost
.在我的例子中,我试图访问
localhost
上的服务。 Apparently the HTTP client tries to connect to the IPv6 localhost first before connecting to its IPv4 equivalent (source: https://github.com/jchristn/restwrapper ), which causes slowdown.显然,HTTP 客户端在连接到其等效的 IPv4 之前首先尝试连接到 IPv6 本地主机(来源: https://github.com/jchristn/restwrapper ),这会导致速度下降。
Changing localhost
to 127.0.0.1
in my case cut off 2000ms of delay, although there is still maybe ~120ms delay on the first request.在我的例子中,将
localhost
更改为127.0.0.1
可以减少 2000 毫秒的延迟,尽管第一个请求可能仍有约 120 毫秒的延迟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.