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.
12 31513
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)
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.
Hi,
i see what you mean.
i made a console app to test it - class Program
-
{
-
static void Main(string[] args)
-
{
-
for (int i = 0; i < 100; i++)
-
{
-
DateTime st1 = DateTime.Now;
-
Thread.Sleep(10);
-
DateTime st2 = DateTime.Now;
-
TimeSpan ts = st2.Subtract(st1);
-
Console.Write(ts.Milliseconds.ToString() + ".");
-
}
-
}
-
}
the first time the loop executes the timespan is actually 12ms. and there on always 10ms
what i then did was - class Program
-
{
-
static void Main(string[] args)
-
{
-
DateTime st1 = DateTime.Now, st2 = DateTime.Now;
-
TimeSpan ts;
-
for (int i = 0; i < 100; i++)
-
{
-
st1 = DateTime.Now;
-
Thread.Sleep(10);
-
st2 = DateTime.Now;
-
ts = st2.Subtract(st1);
-
Console.Write(ts.Milliseconds.ToString() + ".");
-
}
-
}
-
}
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
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
You are not going to find anything more accurate then Thread.Sleep()
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.
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
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.
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?
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). -
Dim oStopWatch As New System.Diagnostics.Stopwatch()
-
While True
-
Dim StartTime As DateTime = Now()
-
Console.WriteLine("Start: " & StartTime)
-
oStopWatch.Start()
-
While oStopWatch.ElapsedMilliseconds < 10
-
'Do Nothing
-
End While
-
If oStopWatch.ElapsedMilliseconds <> 10 Then
-
Console.WriteLine("Failed")
-
End If
-
End While
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.
@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.
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
| |