views:

303

answers:

3

Hello everyone,

I am using VSTS 2008 + C# + .Net 3.5 to develop a Windows Service application. The code is very simple below, and I find when File.Copy throws exception (e.g. path not valid, no permission, etc.), the service will crash and pop-up a dialog to let me debug. My confusion is, I think unhandled exception of a thread created by a Windows service will never make the service crash. Why my service crashes and the debug dialog pop-up?

   public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            Thread t = new Thread (WriteF);
            t.Start();
        }

          static void WriteF() {
              File.Copy("dummy.txt", @"\\somelocation\dummy.txt");
          }

        protected override void OnStop()
        {
        }
    }

thanks in advance, George

+2  A: 

Your file copy operation is throwing an exception which is not being caught. Simple as that. The service will fail unless you wrap the File.Copy operation in a try catch block. It does not matter that the operation is being performed on a background thread. I would also suggest adding some logging otherwise you won't discover why it's failing.

IanT8
I am not sure if this is the same, but we have had before from a service we create a thread Main thread (which runs as to not hold up the service). It will then retrieve a list of users, and loop the users, creating a thread for each user to perform the task. In the events where a thread had an unhandled exception, the other threads disd complete. Am i issing something, or is this different to what the question was?
astander
Exception thrown from any threads of the Windows service will make the Windows service crash?
George2
+2  A: 

I think unhandled exception of a thread created by a Windows service will never make the service crash

Your assumption is simply wrong. Unhandled exceptions in a Windows service will cause it to crash. The debug dialog appears because there is a debugger configured on your system. From .NET 2.0 onwards, an unhandled exception on any thread shuts down the whole application. Just because you're using a thread doesn't mean exceptions in the thread will magically go away.

blowdart
Exception thrown from any threads of the Windows service will make the Windows service crash?
George2
Yes. This is not unique to services, it's the same for any application.
blowdart
Thanks, question answered!
George2
A: 

You start a new thread for running the code in WriteF. If this code fails with an exception, the runtime will try to find an exception handler by unwinding the stack for that particular thread. If it fails in locating a handler, the runtime has no option but the report an unhandled exception and thus the process is terminated. Remember exception handling is per thread. This is not a Windows Service issue.

Brian Rasmussen