views:

101

answers:

3

in the ServiceStart() call of a windows service, I create a thread and start it.
Thread1 = New TThread1(false)

In the Execute procedure of the subthread, there is a loop that runs forever and does that the service is supposed to do.

The problem is that when I get an error in this thread, I want to terminate the thread, and stop the service too.

How can I get the service to stop itself if a thread that it has started stops (fails).

A: 

A possibility is to use watchdog timers: in your thread you reset the timer (eg. every time you enter the loop). when interval of timer is expired, you know that the thread is probably not working anymore, so you can restart the service or what ever...

Marcel
A: 

A better approach might be to catch exceptions in the thread and log them. Or you could catch the exception, log it, then stop the service. That way you are in control of the service stopping and you also have some insight into the errors being generated.

Sean Carpenter
A: 

make a call to stop service :

        bool StopService(string svr_name)
        {
            bool ret = false;
            if (svr_name.Length > 0)
            {
                try
                {
                    ServiceController sc = new ServiceController(svr_name);

                    if (sc.Status == ServiceControllerStatus.Stopped)
                    {
                        return true;
                    }
                    sc.Stop();
                }
                catch (Exception)
                {
                    return false;
                }
            }
            return ret;
        }
lsalamon