日期:2014-05-18  浏览次数:21223 次

关于HttpWebResponse线程阻塞的问题
程序运行 偶尔会在运行到myRes = (HttpWebResponse)myReq.GetResponse();
这句的时候出现异常进入catch:System.Net.WebException:请求被中止:操作超时此时 这个线程就阻塞了,主线程没反应了。。。
finally里明明已经全部释放了
代码在下方 大牛来吧 !!!!万分感谢
C# code
private bool SendReport(string dttm,string strnewid,string strcontent)//string NewReport
        {
            bool a = false;
            string strresponseid = string.Empty;
            string strdateandid = string.Format("{0:yyyyMMddHHmmss}",dttm)+strnewid;
            strcontent = strcontent.Replace(" ","<bl>");//替换空格
            strcontent = strcontent.Replace("\r\n","<en>");//替换换行
            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "report="+strdateandid+":"+strcontent;
            byte[] str = encoding.GetBytes(postData);//编码字符串
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(frmIP.PostIP);
            myReq.Method = "POST";//设置请求的方法
            myReq.ServicePoint.ConnectionLimit = 20;
            myReq.ContentType = "application/x-www-form-urlencoded";//一个疑问
            myReq.ContentLength = str.Length;//获取字符长度
            myReq.ServicePoint.Expect100Continue = false;
            HttpWebResponse myRes=null;
            
            try
            {
                using (Stream sm = myReq.GetRequestStream())
                {
                    sm.Write(str, 0, str.Length);//向公网写数据
                }
                myRes = (HttpWebResponse)myReq.GetResponse();
                if (strcontent != "CH")
                {
                    using (StreamReader sr = new StreamReader(myRes.GetResponseStream()))
                    {
                        strresponseid = sr.ReadToEnd();
                        //strresponseid = string.Empty;
                        if (strresponseid == "")
                        {
                            ChangeSendSignData(strnewid, dttm, 0);
                        }
                        else
                            ChangeSendSignData(strnewid, dttm, 1);
                    }
                }
                a = true;
            }
            catch(Exception ex)
            {
                ChangeSendSignData(strnewid, dttm, 0);
                txtThrowRong.AppendText(DateTime.Now.ToString() + " POST数据异常,请确认网络连接良好 流水号:"+strnewid+"\r\n");
                txtThrowRong.ScrollToCaret();
                string strErrors = DateTime.Now.ToString() +" POST数据异常\r\n" + "错误报告:" + ex.ToString() + "\r\n\r\n";
                File.AppendAllText("Errors.LOG", strErrors);
                SendErrorsLog(strErrors);
                a = false;
            }
            finally
            {
                if (myReq != null) { myReq.Abort(); }//销毁HttpWebRequest 必须
                if (myRes != null) { myRes.Close(); myRes = null; }
            }
            return a;
        }


------解决方案--------------------
IE中是否正常
重试若干次如果还是下载不了,抛异常
抓包分析看看