C# 在异步中使用HttpWebRequest出现的“正在终止线程”错误的解决方案
最近做接口对接,因需求变化需要用到异步推送信息,就利用委托做了异步。
程序运行过程中时不时出现“正在终止线程”的错误信息,导致两边订单信息不一致,代码如下:
byte[] byteData = Encoding.UTF8.GetBytes(parameters); HttpWebResponse response=null; Stream myResponseStream = null; Stream myRequestStream = null;try { var request=(HttpWebRequest) WebRequest.Create(Url); request.Proxy = null;//不使用代理 request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteData.Length; using (myRequestStream = request.GetRequestStream()) { myRequestStream.Write(byteData, 0, byteData.Length); } response = (HttpWebResponse) request.GetResponse(); myResponseStream = response.GetResponseStream(); //将响应流转成xml对象 XmlDocument doc = new XmlDocument(); if (myResponseStream != null) doc.Load(myResponseStream); //返回xml对象 return doc; } catch (Exception ex) { LogHelper.CreateLog("post信息时出错!信息:" + ex.Message, orderid, httpContext); return null; } finally { if (myResponseStream != null) { myResponseStream.Close(); myResponseStream.Dispose(); } if (response != null) { response.Close(); response.Dispose(); } if (myRequestStream != null) { myRequestStream.Close(); myRequestStream.Dispose(); } }
网上寻找解决方案,基本上都是Response.Redirect导致的错误。我的代码上面并没有这些玩意儿。。。
实在是无法组织语言了,归根到底的原因就是C#中使用多线程使用HttpWebRequest时,默认的连接数只有2。
然后有时候因为对方服务器的原因导致访问超时,如果没有做超时处理的话,request对象就不会被释放,后面便导致一系列的问题。
解决方法之一就是在调用HttpWebRequest对象之前将连接数改大。
System.Net.ServicePointManager.DefaultConnectionLimit = 24
解决后代码:
byte[] byteData = Encoding.UTF8.GetBytes(parameters); HttpWebResponse response=null; Stream myResponseStream = null; Stream myRequestStream = null; System.Net.ServicePointManager.DefaultConnectionLimit = 24; try { var request=(HttpWebRequest) WebRequest.Create(Url); request.Proxy = null;//不使用代理 request.KeepAlive = false;//不建立持久性连接 request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteData.Length; using (myRequestStream = request.GetRequestStream()) { myRequestStream.Write(byteData, 0, byteData.Length); } response = (HttpWebResponse) request.GetResponse(); myResponseStream = response.GetResponseStream(); //将响应流转成xml对象 XmlDocument doc = new XmlDocument(); if (myResponseStream != null) doc.Load(myResponseStream); //返回xml对象 return doc; } catch (Exception ex) { LogHelper.CreateLog("post信息时出错!信息:" + ex.Message, orderid, httpContext); return null; } finally { if (myResponseStream != null) { myResponseStream.Close(); myResponseStream.Dispose(); } if (response != null) { response.Close(); response.Dispose(); } if (myRequestStream != null) { myRequestStream.Close(); myRequestStream.Dispose(); } }
这个个数,有相关说法是CPU的数量*2,具体有待考证,不过已经解决了我的问题。
其他解决方式参考连接:
http://www.cnblogs.com/eaglet/archive/2012/05/18/2507179.html
http://www.cnblogs.com/1971ruru/archive/2012/04/11/2442589.html
http://blog.sina.com.cn/s/blog_3eea4f680100s48d.html