为什么不捕获异常“无法从传输连接读取数据:现有连接被远程主机强行关闭” [英] Why don't catch the exception "Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host"

查看:104
本文介绍了为什么不捕获异常“无法从传输连接读取数据:现有连接被远程主机强行关闭”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个从网页上获取信息的程序。运行很长时间(几个小时)后,我总是得到一个例外无法从传输连接中读取数据:现有连接被远程主机强行关闭,但是,我尝试... Catch ...不会捕获异常导致程序崩溃。

我的代码:

I am doing a program to get information from web page. After running long time(several hours), I always get a exception "Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host", but, my try...Catch... doesn't capture the exception lead to program crash.
My Code:

public string GetPage(string posturl, string encode, string postData, string CompanyName, string currentMainThreadName)
{
    string contentResult = string.Empty;
    string err = string.Empty;
    int couterTry = 0;
    
    Encoding encoding = System.Text.Encoding.GetEncoding(encode);
    byte[] data = encoding.GetBytes(postData);
    
    do
    {
        // Set some request parameter
        // So as to readability, don't put below parameter set into a lonely function  
        this.request = WebRequest.Create(posturl) as HttpWebRequest;
        CookieContainer cookieContainer = new CookieContainer();
        this.request.CookieContainer = cookieContainer;
        this.request.AllowAutoRedirect = true;
        this.request.Method = "POST";
        this.request.Accept = "text/html, application/xhtml+xml, */*";
        this.request.Headers.Add("Accept-Language", "en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3");
        this.request.KeepAlive = true;
        this.request.ContentLength = data.Length;
        this.request.ContentType = "application/x-www-form-urlencoded";
        this.request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko";
        Cookie ck = new Cookie("JSESSIONID", "074B29A53D2368D7C1ABC586821A8FA7");
        ck.Domain = target.Host;
        cookieContainer.Add(ck);
        this.request.Timeout = 60000;
    
        try
        {
            couterTry++;
            // Put post data into stream
            this.outStream = request.GetRequestStream();
            this.outStream.Write(data, 0, data.Length);
    
            // Send request and get relative response data
            this.response = request.GetResponse() as HttpWebResponse;
            // Not untill request.GetResponse(), program begin sending Post request to destination Web page 
    
            if (this.response.StatusCode == HttpStatusCode.OK)
            {
                this.inStream = this.response.GetResponseStream();
                this.SR = new StreamReader(this.inStream, encoding);
                // Return result web page html resource code
                contentResult = this.SR.ReadToEnd();
    
                lock (this.webLogWebLog)
                {
                    this.webLogWebLog.Invoke((MethodInvoker)delegate()
                    {
                        this.webLogWebLog.AppendText(string.Format("{0}: Post: Get web page resource code success! Need to retrieve  infor of :{1}.\r\n", currentMainThreadName, Name));
    
                        this.webLogWebLog.ScrollToCaret();
                    });
                }
    
                this.DisposeStream();
                break;
            }
            else
            {
                this.DisposeStream();
                contentResult = string.Empty;
                
                lock (this.webLogWebLog)
                {
                    this.webLogWebLog.Invoke((MethodInvoker)delegate()
                    {
                        this.webLogWebLog.AppendText(currentMainThreadName + ": Post: Connection fail: this.response.StatusCode:" + this.response.StatusCode + "\r\n");
    
                        if (couterTry < 10)
                        {
                            this.webLogWebLog.AppendText(string.Format("{0}: Post: Re-send Post request after 20 seconds ...,  Name:{1} !!! times:{2}. \r\n", currentMainThreadName, Name, couterTry));
                        }
                        else
                        {
                            this.webLogWebLog.AppendText(string.Format("{0}: Post: Give up getting infor of  Name:{1}, after trying 10 times !!! \r\n", currentMainThreadName, Name));
                        }
    
                        this.webLogWebLog.ScrollToCaret();
                    });
                }
    
                if (couterTry >= 10)
                {
                    break;
                }
            }
        }
        catch (Exception ex)
        {
            this.DisposeStream();
            contentResult = string.Empty;
            err = ex.Message;
    
            lock (this.webLogWebLog)
            {
                this.webLogWebLog.Invoke((MethodInvoker)delegate()
                {
                    if (err.Contains("Thread was being aborted"))
                    {
                        this.webLogWebLog.AppendText(string.Format("---------{0}: was being aborted when send Post request to server! ---------Name{1} \r\n", currentMainThreadName, Name));
                    }
                    else
                    {
                        this.webLogWebLog.AppendText(currentMainThreadName + ":Post: --Exception--:" + err + "\r\n");
    
                        if (couterTry < 10)
                        {
                            this.webLogWebLog.AppendText(string.Format("{0}: Post: Re-send Post request after 20 seconds ...,  Name:{1} !!! times:{2}. \r\n", currentMainThreadName, Name, couterTry));
                        }
                        else
                        {
                            this.webLogWebLog.AppendText(string.Format("{0}: Post: Give up getting  infor of  Name:{1} after trying 10 times !!! \r\n", currentMainThreadName, Name));
                        }
                    }
    
                    this.webLogWebLog.ScrollToCaret();
                });
            }
    
            if (couterTry >= 10)
            {
                break;
            }
        }
    
        Thread.Sleep(20000);
    
    } while (true);
    
    this.DisposeStream();
    
    return contentResult;
}

推荐答案

它是关于你的异步任务的!

异步将在与实例化的内容不同。因此,尝试Catch块在这种情况下无效。

请在此处查看

http://stackoverflow.com/questions/7834271/c-sharp-try- catch-statement-doesnt-capture-exception-when-exception-occurred [ ^ ]
It`s about your Asynchronous Task !
An asynchronous will operate in a different context from the one it was instantiated in.so Try Catch block is not effective in this case.
Check it out here
http://stackoverflow.com/questions/7834271/c-sharp-try-catch-statement-doesnt-capture-exception-when-exception-occurred[^]


谢谢!你向我提供了一个解决问题的条目!!!
Thanks you! you provides me with a entry of resolving problem!!!


这篇关于为什么不捕获异常“无法从传输连接读取数据:现有连接被远程主机强行关闭”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆