HttpWebRequest使用注意(發生阻塞的解決辦法)服務器
HttpWebResponse myResponse = null; Stream reqStream = null; Stream resStream = null; try { byte[] data = System.Text.Encoding.Default.GetBytes(param); myRequest = (HttpWebRequest)WebRequest.Create(url); myRequest.Method = "POST"; myRequest.KeepAlive = true; myRequest.ContentType = "application/octet-stream"; myRequest.ContentLength = data.Length; reqStream = myRequest.GetRequestStream(); reqStream.Write(data, 0, data.Length); reqStream.Close(); myResponse = (HttpWebResponse)myRequest.GetResponse(); resStream = myResponse.GetResponseStream(); data = new byte[512]; int count = 0; UIFactory.zZRK_MODIForm.memStream = new MemoryStream(); while ((count = resStream.Read(data, 0, data.Length)) > 0) { UIFactory.zZRK_MODIForm.memStream.Write(data, 0, count); } resStream.Close(); } catch { } finally { if (resStream != null) { resStream.Close(); } if (reqStream != null) { reqStream.Close(); } if (myResponse != null) { myResponse.Close(); } }
你們看下這段程序,有問題嗎?乍一看,好像沒有什麼問題,全部的流都釋放了,Response也釋放了。。不過若是你寫個循環無限次發起請求,你會發現,運行不了幾回就阻塞了。爲何呢?你們看下面的代碼 app
HttpWebRequest myRequest = null; HttpWebResponse myResponse = null; Stream reqStream = null; Stream resStream = null; try { byte[] data = System.Text.Encoding.Default.GetBytes(param); //想服務器端發送請求,獲取照片信息 myRequest = (HttpWebRequest)WebRequest.Create(url); myRequest.Method = "POST"; myRequest.KeepAlive = true; myRequest.ContentType = "application/octet-stream"; myRequest.ContentLength = data.Length; reqStream = myRequest.GetRequestStream(); reqStream.Write(data, 0, data.Length); reqStream.Close(); myResponse = (HttpWebResponse)myRequest.GetResponse(); resStream = myResponse.GetResponseStream(); data = new byte[512]; int count = 0; UIFactory.zZRK_MODIForm.memStream = new MemoryStream(); while ((count = resStream.Read(data, 0, data.Length)) > 0) { UIFactory.zZRK_MODIForm.memStream.Write(data, 0, count); } resStream.Close(); } catch { } finally { if (resStream != null) { resStream.Close(); } if (reqStream != null) { reqStream.Close(); } if (myResponse != null) { myResponse.Close(); } if (myRequest != null) { myRequest.Abort(); } }
多了些什麼?多了這個url
if (myRequest != null) { myRequest.Abort(); }
其實不少時候釋放了Stream和Response還不夠,客戶端的Request仍是在保持着,須要等垃圾回收器來回收,因此通常很容易阻塞,致使請求發送不出去。加上這個就是讓HttpWebRequest實例在不須要的時候及時釋放資源。這樣能夠重複使用而不會阻塞。 spa