3

当我向多个客户端发送短信时,它会给出错误操作超时并且错误出现在 HttpWebResponse

我试过 myReq.Timeout = 50000; myReq.ReadWriteTimeout = 50000;

但在第 150 行给出相同的错误错误
Line 148: myReq.Timeout = 50000;
Line 149: myReq.ReadWriteTimeout = 50000;
Line 150: HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
Line 151: System.IO.StreamReader respStreamReader = new System.IO.StreamReader(myResp.GetResponseStream());
Line 152: string responseString = respStreamReader.ReadToEnd();

4

1 回答 1

18

这很可能是问题所在:

HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();

WebResponseimplements IDisposable,所以你应该using为它使用一个语句(以及StreamReader你从流中创建的)。如果您保持WebResponse打开状态,它将占用从连接池到该主机的连接,并且您可能会以这种方式结束超时。固定代码如下所示:

string responseString;
using (var response = myReq.GetResponse())
{
    using (var reader = new StreamReader(response.GetResponseStream())
    {
        responseString = reader.ReadToEnd();
    }
}

即使抛出异常,这也会关闭流和响应,因此您将始终及时清理资源(在这种情况下将连接释放回池)。

于 2013-03-19T07:11:04.487 回答