Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Thread.Sleep() in a Windows Service

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.

like image 490
matt Avatar asked Jun 15 '09 20:06

matt


People also ask

Why thread sleep is not recommended?

Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.

What's thread sleep () in threading?

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 .

Does thread sleep block other threads?

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.

How do you call a sleep method in C#?

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.


1 Answers

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.

like image 103
Mitchel Sellers Avatar answered Oct 13 '22 23:10

Mitchel Sellers