彻底解决WebRequest的GetResponse阻塞问题 Feb 16th, 2012 | Comments 第一版 //第一版,没有释放基础流 WebRequest wr = WebRequest.Create(URL); try { WebResponse res = wr.GetResponse(); /* * do something */ } catch(WebException ex) { throw ex; } 第二版 //第二版,只释放了response WebRequest wr = WebRequest.Create(URL); try { WebResponse res = wr.GetResponse(); /* * do something */ res.Close(); } catch(WebException ex) { res.Close(); throw ex; } 第三版 //正确释放request和response WebRequest wr = WebRequest.Create(URL); try { WebResponse res = wr.GetResponse(); /* * do something */ res.Close(); wr.Abort(); } catch(WebException ex) { res.Close(); wr.Abort(); throw ex; } 第四版 //代理走不通的情况下,会导致导致阻塞 WebRequest wr = WebRequest.Create(URL); //Proxy may block the http request wr.Proxy = null; try { WebResponse res = wr.GetResponse(); /* * do something */ res.Close(); wr.Abort(); } catch(WebException ex) { res.Close(); wr.Abort(); throw ex; } 第五版 //多线程并发时,默认最多只能建立两个持久连接,后续请求也会阻塞, //增大默认连接数限制可解决此问题 //C#默认只允许两个持久连接,http协议的RFC文档也有此建议 System.Net.ServicePointManager.DefaultConnectionLimit = 256; WebRequest wr = WebRequest.Create(URL); try { WebResponse res = wr.GetResponse(); /* * do something */ res.Close(); wr.Abort(); } catch(WebException ex) { res.Close(); wr.Abort(); throw ex; }