【发布时间】:2020-07-09 04:20:22
【问题描述】:
阅读其他答案后,我不明白为什么 SendAsync 这么慢。
从 Postman 调用相同的端点,我在 160 毫秒内得到响应。
从下面的代码调用,需要 10 秒。我正在使用 C# 桌面应用程序进行调用。
public static async Task<string> GetToken()
{
var url = "....";
var dict = new Dictionary<string, string>();
dict.Add("username", "foo");
dict.Add("password", "bar");
using (var client = new HttpClient(
new HttpClientHandler
{
Proxy = null,
UseProxy = false
}))
{
//bypass SSL
ServicePointManager.ServerCertificateValidationCallback = new
RemoteCertificateValidationCallback
(
delegate { return true; }
);
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req); //10 seconds here!
if (res.StatusCode != HttpStatusCode.OK)
return string.Empty;
var token = await JsonConvert.DeserializeObject<TokenResponse>(res.Content.ReadAsStringAsync());
return token.access_token;
}
}
【问题讨论】:
-
using (var req = new HttpRequestMessage(...)) { ... }。 Using objects that implement IDisposable -
using (var client = new HttpClient ...- 错误,因为HttpClient旨在为每个应用程序实例化一次,而不是每次使用。 -
@aepot 你在这两点上都是正确的,但这不会导致延迟。
-
@aepot,问题是要实例化每个请求。谢谢。
-
@aepot,我会很感激的。