我使用这段代码片段来验证URL中指定的文件是否存在,并在每个用户上每隔几秒钟尝试一次。有时(大多数情况下是在有大量用户使用网站时)该代码不起作用。
[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();
}
当我查看Windows事件日志时,发现有几个错误:
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
当我重启IIS时,事情会正常工作,直到下一次发生这种情况。
using
语句,这将确保它们将被正确处理。try/catch
只是用于避免 Web 方法将异常传播到调用者,并在访问远程 URL 时抛出错误时返回false
。 - Darin Dimitrov