Click here to Skip to main content
15,904,288 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've found several examples of how to write a Windows service, but I haven't found much on error handling in services. What is the best way to handle it if an error occurs that's severe enough that the service should be shut down? The only code I've seen loaded a ServiceControlManager object, looked itself up by checking process IDs and sent itself a stop command. Is there a better way?

Nathan Holt
Posted

Well windows services is not a big deal. It is just running by windows instead of an user. So what you might want to do is;
*Use a try-catch block where you start your process or your service and log the exception as if throws it.
*You can create a global error handler which logs everything your service does.

Some detailed info you can find here;

Exception Management Rules[^]

and some more articles about it;

Exception Handling Articles[^]

And a global exception handler;

Global Exception Handler Code for C#[^] ( this is an extra, since you havent identified a language, I thought it might be useful..)

Good luck.
 
Share this answer
 
Thanks for your answer, but it didn't explain what I wanted. If the background thread that the service is running on exits, Windows can still think the service is running just fine. Does it happen if the whole process exits?

I did find more information by googling "application.threadexception windows service" There's an interesting discussion at http://objectmix.com/dotnet/110512-handling-unhandled-exception-net-service.html[^]. I also found explanations of Application.ThreadException vs AppDomain.UnhandledException at http://stackoverflow.com/questions/2014562/whats-the-difference-between-application-threadexception-and-appdomain-currentdo[^]

For now, I'm going to hope that just calling Environment.Exit is a reasonable way to end the service if there's a fatal error.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900