我正在构建一个定期从网站获取信息的 Windows 服务 当捕获到异常时如何重新开始查找?例如,当互联网随后出现故障时。
代码:
public string cadena(string pagina)
{
try
{
String cadena;
WebRequest myWebRequest = WebRequest.Create(pagina);
myWebrequest = 10000;
WebResponse myWebResponse = myWebRequest.GetResponse();
Stream ReceiveStream = myWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("ISO-8859-1");
StreamReader readStream = new StreamReader(ReceiveStream, encode);
cadena = readStream.ReadToEnd();
readStream.Close();
myWebResponse.Close();
return cadena;
}
catch (WebException error)
{
myTimer.Enabled = true;
return "error";
}
}
public void inicia(object sender, System.Timers.ElapsedEventArgs e)
{
myTimer.Enabled = false;
String strSite = cadena("www.something.com");
//Do something with strSite...
myTimer.Enabled = true;
}
protected override void OnStart(string[] args)
{
myTimer = new System.Timers.Timer();
myTimer.Interval = 1500;
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(inicia);
myTimer.Enabled = true;
}