Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I safely stop a C# .NET thread running in a Windows service?

I am maintaining some code which looks something like this. It's a Windows service which does some work every 30 minutes. The ActualWorkDoneHere method takes about 30 seconds to run, but if it is stopped while running it can leave things in a bad state. What is the best way to prevent that from happening? Should I replace the While(true) with a boolean which is set to false in the onstop method (removing the thread Abort call)? Is there some way to tell if a thread is sleeping?

namespace WorkService
{
    public partial class WorkService : ServiceBase
    {
        private Thread _workerThread = null;

        public WorkService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            _workerThread = new Thread(new ThreadStart(DoWork));
            _workerThread.Start();
        }

        protected override void OnStop()
        {
            _workerThread.Abort();
        }

        static void DoWork()
        {
            int sleepMinutes = 30;

            while (true)
            {
                 ActualWorkDoneHere();

                 System.Threading.Thread.Sleep(new TimeSpan(0, sleepMinutes, 0));
            }
        }
    }
}
like image 640
Stimy Avatar asked Nov 19 '09 17:11

Stimy


People also ask

How do I completely turn off my AC?

Turn off the air conditioner To avoid the AC accidentally turning on, you have to shut it off completely. The way to do this is to find the air conditioner's breaker switch outside; it's usually located under a flip-up lid near the condenser unit. Open the lid and turn the switch to “off.”

Is it safe to turn off air conditioner?

The only time you might consider turning off your air conditioner is when there is a lot of lightning nearby. Shutting off your system may help protect your system from a power surge, but you should be sure to turn your system back on as soon as the storm passes.


1 Answers

When I have something like this, I usually use a ManualResetEvent. This is set in the Stop() call. Then I wait with a timeout:

for (;;)
{
    if (_stop.WaitOne(timeout))
        break;
    DoSomething();
}
like image 97
Roger Lipscombe Avatar answered Nov 10 '22 16:11

Roger Lipscombe