Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between System.Threading.Timer and Thread.Sleep() in ASP.NET c# [duplicate]

Possible Duplicate:
Compare using Thread.Sleep and Timer for delayed execution

I am considering whether to use a System.Threading.Timer or Thread.Sleep in my ASP.NET Web Application. I looked for the differences of them. Period or the Sleep will be 100ms. AFAIK if I use a Timer it will not block running thread, but Sleep will block running thread.

Since the interval is very small, would it be better to choose Thread.Sleep(150) ?

Edit: I tend to use it like a timer on not thread pool thread. I know Timers will be run on thread pool, but I don't want to keep thread pool thread for such an operation

like image 563
Mehmet Avatar asked Oct 27 '25 23:10

Mehmet


2 Answers

I would recommend reading:

Comparing the Timer Classes in the .NET Framework Class Library

None of the timers will block the running thread, however the frequency at which they tick as a result of activity on the application's main thread differs as described in the above article.

Which you use really depends on the end result you desire! Although Thread.Sleep is viewed by most people as an anti-pattern.

like image 122
ColinE Avatar answered Oct 30 '25 14:10

ColinE


Thread.Sleep() has some uses for which it is vital. These are few and far between, and if you're using any number higher than about 1 as the argument you almost certainly don't have one.

If it's even possible for a timer to be used instead, then you definitely don't have one. Don't block a perfectly good thread when the alternative isn't even difficult.

Do be careful of the case where a timer is triggered while the previous trigger is still running. Depending on the nature of the operation you will want to either:

  1. Ignore this, if the code called is safe for multiple simultaneous calls then this may be fine. Of course, you have to know that it's fine.
  2. Lock on the timer-triggered operation. Be aware that you can end up with a queue of lots of pending operations.
  3. Lock on the timer-triggered operation, try to obtain the lock with a timeout of zero and if you fail then skip it - there's a thread still here from the last time.
  4. Have the timer as a one-off timer that you restart at the end of each call.
like image 38
Jon Hanna Avatar answered Oct 30 '25 15:10

Jon Hanna