2012-07-05 43 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。从其他答案中我可以看出,我并不孤单。

然而,同样的论据可以用来证明我只是做了上面列出的改变。