Handling exceptions in a Windows .Net Service

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Has anybody successfully added a “Catch All†Exception Handler to a Windows
Service?

I’ve tried adding a handler to the AppDomain’s UnhandledException event.
This works Ok in Windows.Net Forms applications, but although this compiles
happily in my Windows Service, it doesn’t do any good.

Has anyone got any better suggestions?
 
In most cases (including the one service I've created) the primary routine of
a service is a timer elapsed event handler. So I use...

private void Timer_Elapsed
(
object sender
,
System.Timers.ElapsedEventArgs e
)
{
try
{
// Service functionality
}
catch ( System.Exception err )
{
// Error handling
}
}
 
Thanks for the reply.

I’ve got to admit that I don’t know C#, but I’m guessing that this wouldn’t
catch exceptions thrown by the InitializeComponent subroutine?

A little background - I was trying to install a known working service on
another server. It wouldn’t start successfully (kept getting error 1053). I
had difficulty tracking down the error as the Event Logs merely reported an
unhandled exception in the service. I eventually discovered that a
FileSystemWatcher that was being initialised in the InitializeComponent
subroutine was set to monitor a directory that didn’t exist on the server in
question.

It would have been very straightforward to discover the cause of this error
if a “catch all†exception handler was in place and writing useful info to
the Event Log.

Any ideas?
 
I built a .net test svc app and had it throw an exception in its start
method...it never showed up in the UE handler. It appears that the code that
invokes that method is wrapping the thread in its own try-catch handler and
writing the failure to the event log, swallowing the exception, shutting
down the service, and then returning back to the service controller. The svc
mgr never reported it as an error - it just said the service started and
then stopped. I don't know that I would call this a bug but it certainly is
unexpected - I would have expected the UE to be reported as a failure.

You should try wrapping all your entry points in try-catch handlers and
handle them locally - I prefer that anyway as I don't care for UEs,
especially in services. Services ought to be the most stable components on
the system, and a UE in a service is definitely not a good thing.
 
Ah, well then we're probably talking about different things then.

A "service" has three parts:

The service routine, which is typically a timer event handler.
The service controller, which starts and stops the service.
And the service installer, which installs the service.

I have found that all three may reside in the same EXE, which is convenient.
 
Back
Top