473,801 Members | 2,582 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

26 New Member
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 32255
Plater
7,872 Recognized Expert Expert
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...ac cording to msdn)
Oct 4 '07 #2
gagonm
26 New Member
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.si nce my application is very much time critical.
Oct 5 '07 #3
Shashi Sadasivan
1,435 Recognized Expert Top Contributor
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 New Member
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 Recognized Expert Expert
You are not going to find anything more accurate then Thread.Sleep()
Oct 5 '07 #6
Motoma
3,237 Recognized Expert Specialist
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 Recognized Expert Top Contributor
If your "engineerin g" 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 New Member
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
lillLeif
1 New Member
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

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

Similar topics

26
2387
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 collection to process in this thread, I was going to do a _thread.Interrupt(); Would this be a better approach to spinning a thread on ?
8
2786
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 routine that loops through the file buffer: for (int i=0;i < _Buffer.length; i++) { // Code here
9
3489
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 chance to execute during this time? What is the difference between the two? I have code that runs in a loop like this: Dim dResetTime As DateTime = DateTime.Now
14
37378
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 continues, but what does this mean in practice for a typical Windows Forms or Windows Service application?? Some people say you should always use the latter.
9
15062
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 the thread to sleep so its not continuously eating CPU time. Is there another alternative to keep the thread from running? These threads are used in a windows service, and when the service is stopped
4
11074
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." My questions: 1. By "other threads" - does the above statement refer specifically and only to other threads in the current AppDomain?
2
1821
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 thread ABC needs to get thread XYZ's quick attention. My first attempt at this was to have thread ABC merely set a global flag variable that thread XYZ would check at specific points in its execution, and if it saw that the flag was set it would take...
2
3376
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 sitting in the sleep command and not able to be interrupted. When the time came to set the semaphore flag to false (stopping the thread), my program would have to wait up to the entire sleep time to break out of the loop. I have finally found...
0
9558
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10524
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10298
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10278
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10055
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7594
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6833
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4265
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.