0

What's the best way in asp.net c# to achieve the following, that does not involve Thread.Sleep() ?

while (runCriteria)
{
 ...
    run some code to display something
 ...
 wait for x seconds
}

I've searched online and everything appears to use incredibly complex (at least to me) async timer events etc., which seems like overkill.

user2007841
  • 45
  • 1
  • 8
  • 6
    What's wrong with `Thread.Sleep()`? `Thread.Sleep` does not block any other thread, it only blocks the current thread which is the current request. – Tim Schmelter Feb 24 '14 at 15:52
  • 2
    Can you provide some info as to *why* you prefer not to use `Thread.Sleep`? Or why you need to *wait* at all? – rae1 Feb 24 '14 at 15:57

3 Answers3

2

If you're in .NET 4.5 asynchronous code, consider

await Task.Delay(delayTime);

See MSDN docs here.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
0

Create some shared resource like mutex or semaphore or monitor etc. that will always be unreachable for your threads and acquire(wait for) it with the timeout.

lavrik
  • 1,456
  • 14
  • 25
  • There aren't multiple threads per page request. There's only one. – Servy Feb 24 '14 at 16:03
  • The purpose of these tools is to synchronize access to shared resources for multiple threads. If you don't have multiple threads, there's no reason to use them. – Servy Feb 24 '14 at 16:06
  • 1
    Sure, and the purpose of threadSleep is to sleep :) but the author of question is looking for an alternative way to wait. When using sync approach usually spinWait will be used internally, which is similar to @stepandohnal anwser. – lavrik Feb 24 '14 at 16:09
  • These tools are potentially going to spinwait for just a little bit, in the case that the lock is released very quickly, but then it will move on to actually put the thread to sleep, making it virtually identical to `Thread.Sleep` if you know you'll be waiting for several seconds. If anything, it'll be a bit worse, while still being very similar. – Servy Feb 24 '14 at 16:12
0

You can use Thread.SpinWait. It adds nop instructions, so there wont be a context switch.

stepandohnal
  • 457
  • 4
  • 13
  • 2
    This is potentially useful for waiting for very short periods of time. On the order of a few microseconds. Waiting for several full seconds is not something to be done with a spinwait. – Servy Feb 24 '14 at 16:07