Search code examples
c#urlhttpresponsegetresponse

A timed out Error on GetResponse() in third run


I have a thread that runs periodically every 60 seconds. This thread is getting response from a web url. Everything is fine until the third run. It doesn't work anymore and shows this error :

"The operation has timed out"

This is my code and error found on line 5. Thanks!

string sURL;
sURL = "http://www.something.com";
WebRequest wrGETURL;

wrGETURL = WebRequest.Create(sURL);
HttpWebResponse http = (HttpWebResponse)wrGETURL.GetResponse();

Stream objStream = null;
objStream = http.GetResponseStream();

Solution

  • You might want to consider using the using statement:

    string sURL;
    sURL = "http://www.something.com";
    
    using (WebRequest wrGETURL = WebRequest.Create(sURL))
    {
        using (HttpWebResponse http = (HttpWebResponse)wrGETURL.GetResponse())
        {
            Stream objStream = http.GetResponseStream();
    
            //etc.
        }
    }
    

    it guarantees that the Dispose method is called, even in case a exception occurs. (https://msdn.microsoft.com/en-us/library/yh598w02.aspx)

    The reason for the timeout is probably that your server has a limit of x simultaneous requests. Due to the improper disposure, the connection will stay open longer then needed. And although the garbage collector will fix this for you, it's timing is often too late.

    That's why I alway's recommend to call Dispose, through using for all objects that implements IDisposable. This is especially true when you use these object in loops or low-memory (low resource) systems.

    Careful with the streams though, they tend to use a decorator pattern and might call Dispose on all its "child" objects.

    Typically applies to:

    • Graphics objects
    • Database connections
    • TCP/IP (http etc.) connections
    • File system access
    • Code with native components, such as driver for usb, webcam's etc.
    • Stream objects