I have a C# Windows Service. I have the following events
protected override void OnStart(string[] args)
{
string url = "http://localhost:8080";
SignalR = WebApp.Start(url);
eventLog1.WriteEntry("Server running on " + url);
}
protected override void OnStop()
{
eventLog1.WriteEntry(LogMessage.Message);
SignalR.Dispose();
}
The problem is that I am doing a
Environment.Exit(1);
when my service code has completed running its operations, I have properties set on my service such that it restarts after 1 minute (when it receives a failure). It seems that when it fails it doesn't actually hit the "stop" event so my log never gets written. Is there a
OnRestart()
event or something like that? I'm trying to figure out how to get my log written out before I exit the service. It would usually write the log when I manually clicked "Stop Service" from the services dialog in Windows. But I am no longer manually clicking stop to end the service, I am automatically restarting it and forcing a error in the service so I don't have to manually stop and re-start it.
You would think I would just be able to do
eventLog1.WriteEntry("blah blah");
before I exit the code, but I can't because It's out of scope and I'm exiting the code in a seperate class :(
Can't you wrap a try/catch block around the section of code which is doing work? If it fails for whatever reason, it jumps in that catch block where you can raise the OnStop() event.
try
{
//Your service code
}
catch (Exception e)
{
OnStop();
}