开发者

WebRequest Exception in .NET

开发者 https://www.devze.com 2022-12-21 22:16 出处:网络
I use this code snippet that verifie开发者_高级运维s 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

I use this code snippet that verifie开发者_高级运维s 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.


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消