Unhandled exception in threaded windows service

J

Jason

Hi all;

I'm creating a Windows Service in VB.NET -- in OnStart() I'm launching
a new thread to actually do the work. Any unhandled exceptions in
that new thread, though, don't seem to show up/get handled anywhere.
I'm new to threading, but is there a way for me to add a generic
handler in the default thread in a service to catch errors for any
threads it spawns? I understand I still need robust error handling in
the method I'm launching, but I'd still like to have a "catch all" in
place in case something gets missed.

Any information would be appreciated.

Best Regards,
Jason
 
J

Jon Skeet [C# MVP]

Jason said:
I'm creating a Windows Service in VB.NET -- in OnStart() I'm launching
a new thread to actually do the work. Any unhandled exceptions in
that new thread, though, don't seem to show up/get handled anywhere.
I'm new to threading, but is there a way for me to add a generic
handler in the default thread in a service to catch errors for any
threads it spawns? I understand I still need robust error handling in
the method I'm launching, but I'd still like to have a "catch all" in
place in case something gets missed.

Have a look at AppDomain.UnhandledException.
 
I

Ian Griffiths [C# MVP]

The most straightforward approach is to put a top-level catch block in your
thread start function. So something like this (I'm a C# guy by the way, so
I apologise for any VB syntax errors..):

' This is the method your OnStart kicks off on
' a new thread
Sub ServiceThreadMain()
Try
... do whatever your service does here
Catch ex As Exception
... Log error, maybe quit process here...
End Try
End Sub

As a general rule, this kind of 'catch all' exception handler is not
something you want to use throughout most of your code, because it prevents
the exception from going any further, and can therefore lose information.
But it is appropriate to have one of these at the very top of your stack -
it's the simplest way of catching otherwise unhandled exceptions.

I'm not a huge fan of the AppDomain.UnhandledException event approach,
because it seems not to fire until *after* it has given you the opportunity
to attach a debugger in some circumstances.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top