Thread.Sleep problem RRS feed

  • Question

  • I have a thread doing some work and sleeping for a certain amount of time and doing the work again.

    The time it sleeps is a specific length of time minus the time it takes to do the work.

    I found that it always sleeps a couple of millisenconds less than the time I passed to Thread.Sleep.

    Could some one give me some help on this?

    Thursday, March 1, 2007 11:29 AM


All replies

  • The sleep amount is not exact. It depents on how the OS shedules the threads and how much resources and time other threads require. You should sleep less and have a check if the timespan you needed to wait has been reached... That's more reliable.
    Thursday, March 1, 2007 11:41 AM
  • Why not use a timer instead?

    The System.Timers namespace Timer class raises its Elapsed event on a new ThreadPool thread.


    There is also a Timer class in System.Threading namespace


    Slight differences but in general quite similar. There is also yet another one in the System.Windows.Forms namespace.

    Thursday, March 1, 2007 1:49 PM
  • Is there a formal assessment on the accurance of server based timer? The Form based timeer has accuracy of 5ms. Server based timer is said to be "much more accurate", but i couldn't find a quantitive discussion.
    I looked into accurate timing before and the old solution was to use API calls such as QueryPerformanceCounter and QueryPerformanceFrequency. On the other hand, the System.Diagnostics.Stopwatch provides accurate timing, quote from MS document
    "The Stopwatch class assists the manipulation of timing-related performance counters within managed code. Specifically, the Frequency field and GetTimestamp method can be used in place of the unmanaged Win32 APIs QueryPerformanceFrequency and QueryPerformanceCounter.”.
    Thursday, March 1, 2007 3:04 PM