Handle exception on service startup
if you are running .NET 2.0 or higher, you can use ServiceBase.Stop to stop the service from OnStart. Otherwise call Stop from a new thread.
ref [devnewsgroups] (http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic50404.aspx)
(news group gone)
If the main thing you want is for the Services window to report that there was an error, from what I've tried (.NET3.5 on Windows 7), the only way to do this is by setting the ExitCode
. I recommend setting it to 13816, since this results in the message, "An unknown error has occurred." See the windows error codes.
The sample below accomplishes three things.
- Setting ExitCode results in a useful message for the end-user. It doesn't affect the Windows Application log but does include a message in the System log.
Calling Stop results in a "Service successfully stopped" message in the Application log.
throwing the exception results in a useful log entry in the Application log.
protected override void OnStart(string[] args) {
try {
// Start your service
}catch (Exception ex) {
// Log exception
this.ExitCode = 13816;
this.Stop();
throw;
}
}