最近做接口對接,因需求變化需要用到異步推送信息,就利用委托做了異步。
程序運行過程中時不時出現“正在終止線程”的錯誤信息,導致兩邊訂單信息不一致,代碼如下:
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