1

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();
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
mrasoolmirza
  • 787
  • 1
  • 6
  • 22
  • 1
    You might want to check if any of these objects implement the `IDisposable` interface. If so, call the `Dispose` method. (excpecially wrGETURL, be carefull with the streams, they shouldn't be closed before the connection has finished.) – Stefan Aug 12 '15 at 10:48
  • Thanks! but could you please tell me how can i do this? i'm new in C# – mrasoolmirza Aug 12 '15 at 10:58
  • I add a line http.dispose(); at the end of function and it is working well. Thanks again! – mrasoolmirza Aug 12 '15 at 11:04

2 Answers2

0

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
Stefan
  • 17,448
  • 11
  • 60
  • 79
0

The magic number "3" is from here:

The maximum number of concurrent connections allowed by a ServicePoint object. The default connection limit is 10 for ASP.NET hosted applications and 2 for all others.

Hong Duan
  • 4,234
  • 2
  • 27
  • 50