472,804 Members | 956 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,804 software developers and data experts.

Need a accurate alternative of Thread.sleep(time) using c#

I am working on Engineering application where we need thread.sleep() function many times. But since sleep interval is not accurate we need an alternative which can mimick functionality of thread.sleep() .

we have multimedia timer in our code so Please lemme know if I can use that in someway for this purpose.

Any Help would be greatly appreciated.
Oct 4 '07 #1
12 31513
7,872 Expert 4TB
What do mean by Thread.Sleep() interval is not accurate?
It meaures it's time in miliseconds, which is as accurate as a windows-based PC can get. (There ways to try and do smaller timer intervals, but the resolutions of system clocks on windows PCs is generally only a milisecond...according to msdn)
Oct 4 '07 #2
what I mean to say is that thread.sleep(10) can pause current thread for more than 10 milliseconds whereas I want it to to pause thread for exactly for 10 milliseconds.since my application is very much time critical.
Oct 5 '07 #3
Shashi Sadasivan
1,435 Expert 1GB
i see what you mean.
i made a console app to test it
Expand|Select|Wrap|Line Numbers
  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             for (int i = 0; i < 100; i++)
  6.             {
  7.                 DateTime st1 = DateTime.Now;
  8.                 Thread.Sleep(10);
  9.                 DateTime st2 = DateTime.Now;
  10.                 TimeSpan ts = st2.Subtract(st1);
  11.                 Console.Write(ts.Milliseconds.ToString() + ".");
  12.             }
  13.         }
  14.     }
the first time the loop executes the timespan is actually 12ms. and there on always 10ms

what i then did was
Expand|Select|Wrap|Line Numbers
  1. class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             DateTime st1 = DateTime.Now, st2 = DateTime.Now;
  6.             TimeSpan ts;
  7.             for (int i = 0; i < 100; i++)
  8.             {
  9.                 st1 = DateTime.Now;
  10.                 Thread.Sleep(10);
  11.                 st2 = DateTime.Now;
  12.                 ts = st2.Subtract(st1);
  13.                 Console.Write(ts.Milliseconds.ToString() + ".");
  14.             }
  15.         }
  16.     }
The output for this was 10 always.
Lesson: initialise all values after thread.sleep or else it will eat time.

does this help you anyhow?

Oct 5 '07 #4
hi Sri
Much Thanks for your time and effort but normally this will be true when you are working in small applications but in my case there are no of forms having timers and different threads running concurrently.so in these cases this doesn't work properly.
Anyways I will look into my code for your suggestion But it will be nice if I can have some stuff which always give me correct result.

Thanks again
Oct 5 '07 #5
7,872 Expert 4TB
You are not going to find anything more accurate then Thread.Sleep()
Oct 5 '07 #6
3,237 Expert 2GB
It is not that the Thread.Sleep() function is inaccurate; it is designed to pause a thread for at least the number of milliseconds you specify. You cannot be sure that the underlying OS's scheduler will allow the thread to resume immediately: if you put the system under significant load, or a large number of threads, it is quite likely you will see Threads sleeping a lot longer than you expect. It is not that the thread is actually sleeping longer than you specified, it is that has not received its next time slice of execution.
Oct 5 '07 #7
Shashi Sadasivan
1,435 Expert 1GB
If your "engineering" application is to wait for a certain time....is it that you are to send the next set of commands after the specified interval, to an external piece of hardware?
If so, then send the instruction to that hardware to wait for that period of time. Nothing can get more accurate tha that then.

If it is only an internal process, then there should be a different way than making your application sleep off for a while

Oct 5 '07 #8
can u please lemme know if I can approach in some otherway to achieve same result.(ex using accurate timers with events etc) from my code.again I m facing timing related issue.
code is like this.(in c#)
//here I need delay of 10 msec exact (this delay interval is also
//varying throughout code

I want statement B to be called exactly 10 msec after statement A is executed.

if some c++ code can be used in unsafe context then that would also solve my purpose.
Oct 15 '07 #9
One possible solution would be to never leave the thread, which might be okey if you just need a short sleep. Just setup a while loop and check if wanted time has passed etc.

But this requires some way to make a section atomic. Does anyone know any way to do this in .NET?
Sep 8 '08 #10
797 Expert 512MB
One possible solution would be to never leave the thread, which might be okey if you just need a short sleep. Just setup a while loop and check if wanted time has passed etc.

But this requires some way to make a section atomic. Does anyone know any way to do this in .NET?
Given that the timespan required is short, and that it is time sensitive, I'd say that passing out to another thread is not the correct approach. The second you give up a thread's processing to other system resources and threads, you can never guarantee getting the resources allocated back to your thread in the required time. So you're going to have to write some kind of loop. I did a few trials and even that is sketchy... I used to have a high speed timer function for measuring performance of components and functions, but I appear to have mislaid it. It relied on Win32/API programming, so it's not fabulously easy to understand.

I found another route: The System.Diagnostics.StopWatch... I just ran this block of code for a few minutes to test and it appears as though it's working... I can't guarantee it will always work, but it seems reasonably stable under a relatively normal load (i.e. my iTunes, 5 instances of Visual Studio Enterprise Edition, SQL Server 2005 under a usual every day load, Email, Excel, A couple of instances of Notepad, 2 screens).

Expand|Select|Wrap|Line Numbers
  1. Dim oStopWatch As New System.Diagnostics.Stopwatch()
  2. While True
  3.     Dim StartTime As DateTime = Now()
  4.     Console.WriteLine("Start: " & StartTime)
  5.     oStopWatch.Start()
  6.     While oStopWatch.ElapsedMilliseconds < 10
  7.         'Do Nothing
  8.     End While
  9.     If oStopWatch.ElapsedMilliseconds <> 10 Then
  10.         Console.WriteLine("Failed")
  11.     End If
  12. End While
Sep 8 '08 #11
Use Thread.SpinWait(....)
SpinWait not take out the thread from OS scheduling queue like Thread.Sleep.
It just keep busy the cpu for a specific iterations in a loop.
before using it u find ur cpu clock speed and then doing little Maths u can find interval.
Feb 14 '09 #12
229 Expert 100+
If you already have a wrapper for winmm.dll, then you might use timeSetEvent.

System.Threading.Timer should also be more precise than System.Windows.Forms.Timer, because it doesn't queue event handlers to the GUI thread (I'm not sure which timer it uses internally).

System.Diagnostics.StopWatch internally uses QueryPerformanceCounter, so it's really precise, but you can't pass a callback function to be executed, so instead you will have to query it repeatedly.
Feb 16 '09 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

by: news.microsoft.com | last post by:
Hi, Currently I have a thread thats spinning and doing a Thread.Sleep(someTime). I was thinking of changing this to Thread.Sleep(Timeout.Infinite); then when I have actual data in a...
by: Cider123 | last post by:
I ran into a situation where my Window Service had to process 100,000+ files, when I first noticed I needed to tweak various routines. Everything runs fine, but here's what I ran into: In the...
by: Chris Dunaway | last post by:
According to the docs, calling Thread.Sleep(0) causes the thread to be "suspended to allow other waiting threads to execute." What happens if I call Thread.Sleep(500)? Do other threads not get a...
by: Joe | last post by:
Does anyone know the difference, in practical terms, between Thread.Sleep (10000) and Thread.CurrentThread.Join (10000)?? The MSDN says that with Join, standard COM and SendMessage pumping...
by: Andy | last post by:
Hi, I have some things that act in a typical producer consumer fashion. When they have work to do, I want them doing that, but if there's no work, I'm currently using Thread.Sleep to cause...
by: Frankie | last post by:
This is from MSDN online (http://msdn2.microsoft.com/en-us/library/d00bd51t.aspx): "Specify zero (0) to indicate that this thread should be suspended to allow other waiting threads to execute." ...
by: =?Utf-8?B?UmF5IE1pdGNoZWxs?= | last post by:
Hello, I have a thread ABC that starts another thread XYX. Thread XYZ monitors various things and if there is no work to do it calls Thread.Sleep to sleep for a minute or so. Occasionally...
by: Steve | last post by:
Hi All, I've been trying to come up with a good way to run a certain process at a timed interval (say every 5 mins) using the SLEEP command and a semaphore flag. The basic thread loop was always...
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
by: lllomh | last post by:
How does React native implement an English player?
by: Mushico | last post by:
How to calculate date of retirement from date of birth

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.