1

I am not using Thread so can't use thread.sleep() method.. Its part of my program where I need to introduce some delay .. Not precisely 1mSec but almost that ..

which is the standard method that is known to be so??

Rookie Programmer Aravind
  • 11,952
  • 23
  • 81
  • 114
  • 2
    As you can see from the answers there are plenty of problems with 'introducing a delay'. It might help if you could indicate what it is for. – H H Aug 09 '10 at 13:33
  • You'll need to P/Invoke timeBeginPeriod(1) to get the Thread.Sleep() accuracy down to a millisecond. Use pinvoke.net for the declaration. – Hans Passant Aug 09 '10 at 13:59
  • @Hans, thanks for the response, I just wanted to know the method, I have got to use it in many programs, well I will follow up your suggestion. :) if you could post it as an answer .. I would be able to accept it as an appreciation. – Rookie Programmer Aravind Aug 28 '10 at 14:48

5 Answers5

9

You are always using a thread. Every application has at least one thread, so Thread.Sleep will work fine.

btlog
  • 4,760
  • 2
  • 29
  • 38
  • @Henk I might be taking some liberties on the "but almost" part of the question :) – btlog Aug 09 '10 at 13:14
  • 2
    One thing worth noting is that you could potentially 'sleep' for 20 ms at any time without even calling Sleep, due to a context switch by Windows' preemptive multitasking scheduler. If there is an upper bound on the acceptable delay, there is already a bigger problem. – Dan Bryant Aug 09 '10 at 13:23
5

I am not using Thread so can't use thread.sleep() method

Not sure you you say that -- you can use Thread.Sleep anywhere you like.

Tim Robinson
  • 53,480
  • 10
  • 121
  • 138
3

Just so you know, a 1msec sleep isn't guaranteed be exactly 1msec, in fact it's very improbable due to it being such a small time. The thread.sleep(x) states x as a minimum sleep time, if you wan't a much more exact sleep you might want to look into win32 multimedia timers: http://msdn.microsoft.com/en-us/library/dd742877.aspx

Blam
  • 2,888
  • 3
  • 25
  • 39
1

Don't sleep 1msec. It will not be accurate at all. Read for instance this article or this

Thread.sleep will always suspend the current thread. Keep in mind that it's not a good idea to use Sleep on a GUI thread (if your app is a winform app).

Community
  • 1
  • 1
jgauffin
  • 99,844
  • 45
  • 235
  • 372
0

If you are just trying to provide an opportunity for thread switching, then use Thread.Sleep(0). (This is equivalent to Thread.Yield() in Java.)

Edit: actually seems like they've added Thread.Yield() in .NET 4.

Paul Ruane
  • 37,459
  • 12
  • 63
  • 82