Using Thread.Sleep() in a Windows Service Using Thread.Sleep() in a Windows Service multithreading multithreading

Using Thread.Sleep() in a Windows Service


I would use a timer, Thread.Sleep, could cause a blocking piece that could prevent the service from shutting down.

If the interval is that wide spread, and regular, you might just schedule it as well. But if you are talking about long, non-consistent intervals, then yes a Timer would be better.


Since a service may be asked to stop at any time by the Service Control Manager, your thread should always be ready to respond to these requests, so you should not use Thread.Sleep(). Instead, create a manual-reset event in the main thread and use its WaitOne method with a timeout in your worker thread. WaitOne will return false when the time expires.

When your service class's OnStop or OnShutdown methods are called, set the event and that will cause WaitOne to return true and you can then exit your worker thread.


It's generally regarded as bad practice to use Thread.Sleep() in a lot of cases.

If you want the service to run in the background, you should use a timer.

If the service only needs to be run at scheduled intervals, I'd recommend you look into using Windows task scheduler to allow Windows to run the application when you need it to.