WebRequest Exception in .NET

4

I use this code snippet that verifies if the file specified in the URL exists and keep trying it every few seconds for every user. Sometimes (mostly when there are large number of users using the site) the code doesn't work.

    [WebMethod()]
    public static string GetStatus(string URL)
    {
        bool completed = false;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            try
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    completed = true;
                }
            }
            catch (Exception)
            {
                //Just don't do anything. Retry after few seconds
            }
        }

        return completed.ToString();
    }

When I look at the Windows Event logs there are several errors:

Unable to read data from the transport connection. An existing connection was forcibly closed

The Operation has timed out

The remote host closed the connection. The error code is 0x800703E3

When I restart the IIS, things work fine until the next time this happens.

c#
asp.net
iis
exception
scalability
asked on Stack Overflow Feb 27, 2010 by DotnetDude • edited Feb 27, 2010 by Jim Counts

1 Answer

4

You are putting the try/catch inside the using statement while it's the request.GetResponse method that might throw:

bool completed = false;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
try
{
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            completed = true;
        }
    }
}
catch (Exception)
{
    //Just don't do anything. Retry after few seconds
}
return completed.ToString();
answered on Stack Overflow Feb 27, 2010 by Darin Dimitrov

User contributions licensed under CC BY-SA 3.0