473,405 Members | 2,154 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

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 31983
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

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

Similar topics

26
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...
8
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...
9
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...
14
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...
9
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...
4
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." ...
2
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...
2
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.