[英]HttpWebResponse - disposing of a connection properly
我正在使用C#中的下載管理器,我正在使用多個http請求,並且想知道如何確保連接正確關閉?
在響應流上調用Dispose是否足夠? 我是否也需要致電關閉? 不確定哪里可能出錯,但在某些時候網站會變得反應遲鈍。
謝謝!
將HttpWebResponse
包裝在using塊中:
using(HttpWebResponse response = request.GetResponse())
{
// do stuff here
} // response object is automatically disposed of here.
正如Kyle所提到的,將HttpWebResponse包裝在一個使用塊中。 但是如果GetResponse()拋出異常(例如,在404響應上發生),則需要在異常中獲取HttpWebResponse。
HttpWebResponse webResponse = null;
try {
webResponse = (HttpWebResponse)webRequest.GetResponse();
} catch (WebException e) {
webResponse = (HttpWebResponse)e.Response;
if (webResponse == null) {
// Handle this.
}
}
using (webResponse) {
// Process the response.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.