Windows Service restarted exception

I am creating a Windows service that periodically grabs information from the website How can I start looking again when an exception is caught? for example, when the internet goes down and ends later.

The code:

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;            
            }

      

0


a source to share


1 answer


Here's a very crude example to get you started, so your program will keep running until you get a valid response. There are better ways to do this, but this is the idea you want. Good luck!

myWebResponse = myWebRequest.GetResponse();
while (myWebResponse.ContentLength == -1) {  
  //sleep
 myWebResponse = myWebRequest.GetResponse();
}  

//continue execution

      



You should probably check if the remote site is reachable and poll until it is not available, or interrupt the service's availability. This way you don't have to recover from a thrown exception.

I think the use of exceptions should be reserved for things a little more disastrous for your application.

+1


a source







All Articles