K
K
kamilgarey2013-09-23 12:57:43
.NET
kamilgarey, 2013-09-23 12:57:43

While(true) or Timeout

I wrote it myself, and in the code of others I met the following construction for periodically launching handlers:

while(true){ ... Thread.Sleep(время); }

instead of using TimeOut . (Well, as a rule, there is still a Boolean variable in the predicate, something like stop , but this does not change the essence.)

Are there any "pitfalls" here? It is clear that there is a time shift (so the code needs some time to execute, so we won’t get the exact time intervals between executions, like using a timer).
Any other differences?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Illivion, 2013-09-23
@Illivion

stackoverflow.com/questions/13406435/is-thread-sleeptimeout-infinite-more-efficient-than-whiletrue
msdn.microsoft.com/en-us/library/tttdef8x.aspx

M
mayorovp, 2013-09-23
@mayorovp

If the time is greater than int.MaxValue / 4, then the thread has every chance not to wake up. I'm not sure if this is a pitfall, but I personally ran into it once.
In addition, with fixed intervals, the real frequency can sag very strongly on a loaded system.
Well, the fact that such code takes up a whole thread should not be ignored.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question