The main problem of using an infinite loop is that your service can't be stopped. A proper implementation would do the work within a thread where the loop can be left upon a stop event. It is also necessary that the startup function of a Windows service returns in a timely fashion.
Use
WaitHandle.WaitOne Method (Int32) (System.Threading)[
^] to wait for a single event (the stop event) or
WaitHandle.WaitAny Method (WaitHandle[], Int32) (System.Threading)[
^] to wait for multiple events. Using the timeout parameter you can avoid using a timer and calling
Sleep()
.
private static ManualResetEvent stopEvent = new ManualResetEvent(false);
private static Thread theThread;
protected override void OnStart(string[] args)
{
theThread = new Thread(ThreadFunc);
theThread.IsBackground = true;
theThread.Start();
}
protected override void OnStop()
{
stopEvent.Set();
if (!theThread.Join(10000))
theThread.Abort();
}
private static void ThreadFunc()
{
int timeOut = startDelay;
while (!stopEvent.WaitOne(timeOut))
{
timeOut = 30000;
}
}