468,104 Members | 1,297 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,104 developers. It's quick & easy.

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

26
HI
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 28614
Plater
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
gagonm
26
hi
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
Hi,
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?

cheers
Oct 5 '07 #4
gagonm
26
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
Plater
7,872 Expert 4TB
You are not going to find anything more accurate then Thread.Sleep()
Oct 5 '07 #6
Motoma
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

cheers
Oct 5 '07 #8
gagonm
26
hi
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#)
statementA
//here I need delay of 10 msec exact (this delay interval is also
//varying throughout code
statementB

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
balabaster
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
vekipeki
229 Expert 100+
@gagonm
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

Post your reply

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

Similar topics

26 posts views Thread by news.microsoft.com | last post: by
8 posts views Thread by Cider123 | last post: by
9 posts views Thread by Chris Dunaway | last post: by
14 posts views Thread by Joe | last post: by
9 posts views Thread by Andy | last post: by
4 posts views Thread by Frankie | last post: by
2 posts views Thread by =?Utf-8?B?UmF5IE1pdGNoZWxs?= | last post: by
2 posts views Thread by Steve | last post: by
1 post views Thread by Solo | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.