C#使用HttpClient進行Post請求出現(xiàn)超時問題的解決及優(yōu)化
優(yōu)化結(jié)論
我直接上優(yōu)化結(jié)論吧,就不放上老的代碼了。需要從以下幾個點來優(yōu)化。
單例HttpClient
問題:如果 HttpClient 實例頻繁創(chuàng)建和銷毀,可能導(dǎo)致連接池中的資源被占滿,新的請求需要等待釋放資源,從而造成長時間的延遲。
首先單例HttpClient,每次請求都會創(chuàng)建一個新的 HttpClient 實例。HttpClient 的短生命周期會導(dǎo)致以下問題:
1,頻繁建立和銷毀連接,無法復(fù)用已有的連接池。
2,增加連接開銷,可能導(dǎo)致長時間等待(尤其在并發(fā)請求時)。
所以我們直接
private static readonly HttpClient client = new HttpClient
{
Timeout = TimeSpan.FromSeconds(15) // 設(shè)置超時時間
};
連接池耗盡和并發(fā)
合理設(shè)置 ServicePointManager.DefaultConnectionLimit,因為就算是單例的HttpClient也會有連接數(shù)的限制。我們看看這個參數(shù)說明:
// 摘要: // Gets or sets the maximum number of concurrent connections allowed by a System.Net.ServicePoint // object. // // 返回結(jié)果: // The maximum number of concurrent connections allowed by a System.Net.ServicePoint // object. The default connection limit is 10 for ASP.NET hosted applications and // 2 for all others. When an app is running as an ASP.NET host, it is not possible // to alter the value of this property through the config file if the autoConfig // property is set to true. However, you can change the value programmatically when // the autoConfig property is true. Set your preferred value once, when the AppDomain // loads. // // 異常: // T:System.ArgumentOutOfRangeException: // System.Net.ServicePointManager.DefaultConnectionLimit is less than or equal to // 0.
有一句是重點
ASP的默認連接限制是10。. NET托管應(yīng)用程序和其他的都是2。
我可能有時又3-4個并發(fā),可能問題在這里,那么我直接設(shè)置100個就足夠滿足我的程序了。
ServicePointManager.DefaultConnectionLimit = 100; // 調(diào)高默認連接限制
并發(fā)異步
如果你的程序有很高的并發(fā),可能會耗盡你的CPU,那么需要使用異步。
HttpResponseMessage response = await client.PostAsync(url, content);
最終優(yōu)化后
我最終的代碼狀態(tài)如下:
public async Task<string> PostFormResult(string url, string parm)
{
Log("PostFormResult 開始請求: " + url + ", parm: " + parm);
try
{
byte[] buf = Encoding.UTF8.GetBytes(parm);
using (HttpContent content = new ByteArrayContent(buf))
{
//這里我是表單,可以換成json
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
//content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
//添加Token
//client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
HttpResponseMessage res = await client.PostAsync(url, content);
if (res.IsSuccessStatusCode)
{
string json = await res.Content.ReadAsStringAsync();
Log("PostFormResult請求成功: " + json);
return json;
}
else
{
Warning("PostFormResult請求失敗: " + res.StatusCode);
}
}
}
catch (HttpRequestException ex)
{
Warning("請求Post出現(xiàn)錯誤: " + ex.Message);
}
catch (Exception ex)
{
Warning($"請求Post出現(xiàn)錯誤: {ex.Message}");
}
return string.Empty;
}
我的請求會同時出現(xiàn)了4個。所以超過了并發(fā)所以產(chǎn)生了問題,修改后就沒有問題了。
到此這篇關(guān)于C#使用HttpClient進行Post請求總是出現(xiàn)超時問題的解決及優(yōu)化的文章就介紹到這了,更多相關(guān)C# HttpClient進行Post請求出現(xiàn)超時內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于WinForm+Halcon實現(xiàn)圖像縮放與交互功能
本文主要講述在 WinForm 中結(jié)合 Halcon 實現(xiàn)圖像縮放、平移及實時顯示灰度值等交互功能,包括初始化窗口的不同方式,以及通過特定事件添加相應(yīng)功能的詳細步驟和代碼示例,能提升圖像處理應(yīng)用的開發(fā)效率和用戶體驗,需要的朋友可以參考下2025-01-01
C#結(jié)合Free?Spire.PDF實現(xiàn)刪除PDF中的數(shù)字簽名
這篇文章主要為大家詳細介紹了C#如何結(jié)合Free?Spire.PDF實現(xiàn)刪除PDF中的數(shù)字簽名,文中的示例代碼講解詳細,感興趣的小伙伴可以參考一下2026-03-03

