我正在C#中下載管理器,我正在使用多個http請求,並想知道如何確保連接正確關閉?HttpWebResponse - 正確處置連接
在響應流上調用Dispose就足夠了嗎?我是否也需要致電Close? 不知道哪裏的東西可能會出錯,但在某個時候一個網站會變得沒有反應。
謝謝!
我正在C#中下載管理器,我正在使用多個http請求,並想知道如何確保連接正確關閉?HttpWebResponse - 正確處置連接
在響應流上調用Dispose就足夠了嗎?我是否也需要致電Close? 不知道哪裏的東西可能會出錯,但在某個時候一個網站會變得沒有反應。
謝謝!
包裝你HttpWebResponse
在使用塊:
using(HttpWebResponse response = request.GetResponse())
{
// do stuff here
} // response object is automatically disposed of here.
凱爾提到的,包你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.
}
我熟悉使用語句,但在完成後我已經調用Dispose(),有什麼區別嗎? – Meniya 2011-04-25 17:41:21
當你像這樣使用''using'時,你不必擔心自己調用'Dispose',編譯器會爲你處理它。 – 2011-04-25 17:42:53