MyDaftQuestions
MyDaftQuestions

Reputation: 4701

Getting a web response timesout

I've been asked to write a small program which checks that all the pages we have online are not erroring.

To do this, I use the following code (where pathsToCheck is List, each string is a URL like http://www.domain.com/webpage)

foreach (string path in pathsToCheck)
{
    HttpWebResponse response = null;
    try
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(path);
        webRequest.AllowAutoRedirect = true;
        response = (HttpWebResponse)webRequest.GetResponse();

        System.Diagnostics.Debug.Assert(response.StatusDescription == "OK", "Look into this, it doesn't like the response code");

        System.Threading.Thread.Sleep(1000);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed : " + path);
    }
    finally
    {
        Write(--totalPathsToCheck);
    }
}

The problem I am having is it always fails (timesout) from the third item in the list (everything fails from the third). Naturally, I guessed there must be a fault with the third item, but there isn't.

Since the first item doesn't time out, I created a new list, with 5 items, all of the same URL (one I know doesn't time out). The same issue occurs, on the third iteration, it times out and continues to time out for the remainder of the list.

I then decided to test a different URL (on a different domain) and the same issue persists.

I added the sleep to the code, and increased it in-case there were too many requests within a given period but that made no differences.

What should I be doing?

Upvotes: 0

Views: 34

Answers (1)

Kamil Bałdyga
Kamil Bałdyga

Reputation: 161

You need to close your connections. Add

response.Close();

From http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.close.aspx:

The Close method closes the response stream and releases the connection to the resource for reuse by other requests. You must call either the Stream.Close or the HttpWebResponse.Close method to close the stream and release the connection for reuse. It is not necessary to call both Stream.Close and HttpWebResponse.Close, but doing so does not cause an error. Failure to close the stream can cause your application to run out of connections.

Upvotes: 1

Related Questions