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));
}
}
}
}
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.”
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With