許多開發者知道要關閉代理,但不清楚不關閉的具體後果。本文透過實驗揭示:會話通道受限於服務端並發會話配額(預設 10),未關閉代理會耗盡配額導致後續調用超時。
BasicHttpBinding 除外,預設綁定皆建立會話通道。客戶端迴圈建立 20 次代理調用 Add(1,2),不呼叫 Close():
for (int i=1; i<=20; i++) {
var proxy = factory.CreateChannel();
Console.WriteLine($"{i}: {proxy.Add(1,2)}");
// 未關閉!
}
結果:前 11 次成功,第 12 次拋出 TimeoutException(預設 1 分鐘)。原因:服務端 ServiceThrottlingBehavior.MaxConcurrentSessions = 10,加上通道監聽器額外允許 1 個 = 11。
方案 A:調整服務端配額(配置檔)
<serviceThrottling maxConcurrentSessions="100" />
方案 B:客戶端及時關閉代理(推薦)
for (int i=1; i<=2000; i++) {
var proxy = factory.CreateChannel();
Console.WriteLine($"{i}: {proxy.Add(1,2)}");
(proxy as ICommunicationObject).Close(); // 釋放會話
}
結果:2000 次全數成功,無超時。
將 WSHttpBinding 設為 SecurityMode.None(或使用 BasicHttpBinding),建立資料報通道。同樣迴圈 2000 次不關閉代理,全部成功。驗證:MaxConcurrentSessions 僅限會話通道。