gpt4 book ai didi

c# - HttpClient 的 SendAsync 非常慢(不是代理问题)

转载 作者:行者123 更新时间:2023-12-02 03:58:08 36 4
gpt4 key购买 nike

目前,使用 HttpClient 发送 POST 消息大约需要 600 毫秒。这似乎比应有的时间要长得多,因为使用我为了测试而编写的 C 程序(使用简单的套接字)发送相同的 POST 性能明显更好,相同的操作大约需要 37 毫秒,并且代码明显更多。

sw.Start();
HttpResponseMessage result = client.SendAsync(request).Result;
sw.Stop();

这是我的测量方法。我知道我可以使用异步函数,并等待而不是使用任务结果,但是在这种情况下无需担心“阻塞”,并且自发送和接收消息以来使用等待/异步不会更快异步会花费相同的时间。至少,这是我的理解。

这是在函数中使用它的示例:

    public void makeAttempt(string attempt)
{
Stopwatch sw = new Stopwatch();

using (var request = new HttpRequestMessage() { Method = HttpMethod.Post })
{
request.RequestUri = new Uri("https://example.com/page?1");

request.Content = new StringContent("attempt-" + trys.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded");
sw.Start();
HttpResponseMessage result = client.SendAsync(request).Result;
sw.Stop();
}

Console.WriteLine("Request took: " + sw.ElapsedMilliseconds.ToString() + "ms");
trys++;
}

最初,我还在同一语句中的 using block 中使用了 HttpClient 和 HttpClientHandler,但是我读到 HttpClient 应该在多个请求中重用,因此我将它们移至全局范围并在构造函数中初始化它们,如下所示:

HttpClient client;
HttpClientHandler handler;

public Test(CookieContainer jar, WebHeaderCollection heads)
{
cookieJar = jar;
headers = heads;
handler = new HttpClientHandler() { CookieContainer = cookieJar, AllowAutoRedirect = true, Proxy = null, UseProxy = false };
client = new HttpClient(handler);
client.BaseAddress = new Uri("https://example.com/");
client.DefaultRequestHeaders.ExpectContinue = false;
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0");
}

有谁知道这可能是什么原因,或者如何提高此操作的性能?预先感谢您,并将让大家了解我学到的任何最新信息!干杯!

最佳答案

我已将 .NET Core 2.1 SocketsHttpHandler 向后移植到 .NET Framework,并且我观察到 backported implementation 显着提高了性能。在某些情况下,特别是同时发出数十个多个请求时,与 .NET Framework HttpClientHandler 相比。

关于c# - HttpClient 的 SendAsync 非常慢(不是代理问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39693783/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com