2012-07-05 37 views
0

我有一個像這樣如何「使用」使用與「出」參數

private bool VerbMethod(string httpVerb, string methodName, string url, string command, string guid, out HttpWebResponse response) 

的方法我用這個像這樣

HttpWebResponse response; 
    if (VerbMethod("POST", "TheMethod", "http://theurl.com", "parameter1=a", theGuid, out response)) 
    { 
    using (StreamReader sr = new StreamReader(response.GetResponseStream())) 
    { 
     string responseString = sr.ReadToEnd(); 
    } 

它返回一個布爾值,指定如果方法進展順利,並將響應設置爲out參數以獲取數據。

我有時會得到超時,然後後續請求也超時。我看到了這個SO WebRequest.GetResponse locks up?

它推薦了using關鍵字。問題是,用上面的方法簽名,我不知道該怎麼做。

  • 我應該在最後手動調用dispose嗎?
  • 有沒有辦法仍然使用usingout參數?
  • 重寫該方法,所以它不公開HttpWebResponse

回答

6

它返回一個布爾值,指定如果方法順利

那是你的問題。不要使用布爾成功值:如果出現問題,請拋出異常。 (或者說,讓例外冒出來。)

只需更改您的方法以返回響應。

3

如果你想使用using(無例外),只是交換了布爾和響應:

private HttpWebResponse VerbMethod(string httpVerb, string methodName, string url, string command, string guid, out bool canExecute); 


bool canExecute = false; 

using(HttpWebResponse response = VerbMethod("POST", "TheMethod", "http://theurl.com", "parameter1=a", theGuid, out canExecute)) 
{ 
    if (canExecute) 
    { 
    .. 
    } 
} 
0

Assigne默認值out參數立即在函數的開始,並繼續使用using你已經在使用它。

0

你也可以使用

HttpWebResponse response; 
    if (VerbMethod("POST", "TheMethod", "http://theurl.com", "parameter1=a", theGuid, out response)) 
    { 
     using (response) 
     { 
      using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream())) 
      { 
       string responseString = sr.ReadToEnd(); 
      } 
     } 
    } 
0

您可以添加其他using的響應:

HttpWebResponse response; 
if (VerbMethod("POST", "TheMethod", "http://theurl.com", "parameter1=a", theGuid, 
    out response)) 
{ 
    using(response) 
    { 
    using (StreamReader sr = new StreamReader(response.GetResponseStream())) 
    { 
     string responseString = sr.ReadToEnd(); 
    } 
    } 
} 
0

可以做到這一點:

private bool VerbMethod(string httpVerb, string methodName, string url, 
    string command, string guid, out HttpWebResponse response) {} 

HttpWebResponse response = null; 

if(VerbMethod(httpVerb, methodName, url, command, guid, out response) { 
    using(response) 
    { 
    using (StreamReader sr = new StreamReader(response.GetResponseStream())) { 
    } 
    } 
} 

using聲明不要求expre它內部的sion(s)是new對象或方法返回 - 任何表達式都可以。

但是 - 一般要求不火,直到調用GetResponseStream()所以我不能看到你bool回報實際上是做多,確認一個對象被創建的任何其他 - 並有單位沒有點測試運行(!)。因此,最好的辦法是讓該方法返回響應並將其放入using。從其他答案中我可以看出,我並不孤單。

然而,同樣的論據可以用來證明我只是做了上面列出的改變。