目前,使用HttpClient发送POST消息大约需要600毫秒。这似乎比应有的要长得多,因为使用我编写的用于测试(使用简单套接字)的C程序发送相同的POST时,其性能要好得多,相同的操作大约需要37毫秒,并且代码更多。
sw.Start();
HttpResponseMessage result = client.SendAsync(request).Result;
sw.Stop();
这是我的测量方法。我知道我可以使用async函数,然后使用await而不是使用Task结果,但是在这种情况下,无需担心“阻塞”,并且使用await / async不会更快,因为发送和接收消息都是如此异步需要花费相同的时间。至少,这是我的理解。
这里是在函数中使用它的示例:
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++;
}
最初,我在同一条语句中的块内也使用了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"); }
有人知道这可能是什么原因,还是如何提高此操作的性能?在此先感谢您,我们将使所有人都了解我所学到的最新信息!干杯!
目前,使用HttpClient发送POST消息大约需要600毫秒。这似乎比应该的要长得多,因为使用我编写的C程序发送相同的POST以进行测试(使用简单的...
[我已经将.NET Core 2.1 SocketsHttpHandler移植到.NET Framework,在某些情况下,尤其是当同时发出多个多个请求时,与.NET Framework HttpClientHandler相比,我发现backported implementation的性能有了显着提高。