Click here to Skip to main content
15,562,222 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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:
C#
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;
}
Posted
Updated 8-May-14 17:21pm
v2
Comments
Aaron Bo 9-May-14 1:54am    
throw exception location is:
sreader = new StreamReader(httpWebResponse.GetResponseStream(), encoding);
patentResourceCode = sreader.ReadToEnd();

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[^]
 
Share this answer
 
Thanks you! you provides me with a entry of resolving problem!!!
 
Share this answer
 
Comments
Nelek 11-May-14 13:00pm    
Please don't post solutions to chat with people asking or answering. The messages are not always sorted by date, so it can be a bit difficult to follow them correctly.
The best option is to use the "Have a question or comment?" (or the tiny "reply" on another comment). Another advantage is, that the person you write to will get a notification, otherwise it could be that he/she doesn't see your additional message.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900