I'm writing a windows service that needs to sleep for long periods of time (15 hrs is the longest it will sleep, 30 mins is the shortest). I'm currently using Thread.Sleep(calculatedTime) to put my code into sleep mode. Is Thread.Sleep the best option or should I be using a timer? I've been googling this for a while and can't find a concise answer. Since this is a windows service, I don't have to worry about locking the UI, so I can't think of a reason not to use Thread.Sleep.
Any insight would be appreciated.
Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.
Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can't be negative, else it throws IllegalArgumentException .
Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread. Once that interval elapses, the sleeping thread resumes execution. One thread cannot call Thread. Sleep on another thread.
In c#, the sleep method is useful to suspend or pause the current thread execution for a specified time. We can suspend the thread execution either by passing the time in milliseconds or with TimeSpan property like as shown below. TimeSpan ts = new TimeSpan(0,0,1); Thread.
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.
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