关闭来自HTTPS POST请求的响应,但有异常

时间:2013-12-01 18:50:36

标签: c# multithreading winforms https

正如我之前关于在多线程c# can't write POST data to https request中发送HTTPS POST请求的问题所示,我想确保在HTTPS POST请求期间捕获异常时关闭响应。以下是代码段:

public void request_3()
{
     byte[] byteArray3 = Encoding.ASCII.GetBytes(post_data_final3);
     Console.WriteLine(Thread.CurrentThread.Name + " " + "request_2 started");
     HttpWebRequest request3 = (HttpWebRequest)WebRequest.Create(site_URI);
     WebHeaderCollection NewHeaders3 = request3.Headers;
     request3.CookieContainer = new CookieContainer();
     request3.Method = "POST";
     //headers info
     request3.Timeout = 60000;
     request3.ContentLength = byteArray3.Length;
     try
     {
         using (Stream os3 = request3.GetRequestStream())
         {
             os3.Write(byteArray3, 0, byteArray3.Length);
         }
     }
     catch (WebException ex33)
     {
         Console.WriteLine(ex33);
         Console.WriteLine(ex33.Status);
     }
     try
     {
         HttpWebResponse response3 = (HttpWebResponse)request3.GetResponse();
         //response handling
         response3.Close();
     }
     catch (WebException wex3)
     {
         Console.WriteLine(wex3);
         Console.WriteLine(wex3.Status);
     }
}

这里的问题是如果我在响应期间得到异常,那么将使用以下代码:

catch (WebException wex3)
         {
             Console.WriteLine(wex3);
             Console.WriteLine(wex3.Status);
         }

我应该关闭" Catch"阻止像

response3.Close();

或者

wex3.Response.Close();

如果2个响应异常,防止第3次响应冻结?或者是否意味着如果我得到异常响应会自动关闭? 谢谢!

1 个答案:

答案 0 :(得分:1)

使用finally确保响应已关闭,无论try / catch中发生了什么:

HttpWebResponse response3 = (HttpWebResponse)request3.GetResponse();
try
{
    // response handling
}
catch (WebException wex3)
{
    Console.WriteLine(wex3);
    Console.WriteLine(wex3.Status);
}
finally
{
     response3.Close();
}

或者,更好的是,HttpWebResponse实现IDisposable,这意味着您可以让它自己处理:

using (HttpWebResponse response3 = (HttpWebResponse)request3.GetResponse())
{
    try
    {
        // response handling
    }
    catch
    {
        Console.WriteLine(wex3);
        Console.WriteLine(wex3.Status);
    }
}