I need prety simple thing
while (true) {
DoJob();
// wait 1 ms
}
Should I just use Thread.Sleep(1)?
I'm not sure about using Timer because it seems overhead of Timer itself is a little bit more than 1 ms.
Update: I need this delay to be sure that I received the most recent information from network, it's trading software. I need to do something and then I have to wait 1 ms to see what happens. I can wait 1.5 ms, but not 3 ms, that would be too much. It's ok to wait rarely 5 or 10 ms, but in general it should be ~1 ms
Edit -- corrected "most resolution you will get from sleep to about 20 ms, instead of 100 ms
About the most resolution that you will get out of sleep is 100 milliseconds, even if you pass Sleep(1).
For what it's worth, a timer may be more efficient for this -- especially if you have more than 1 thread sleeping (System.Threading.Timer will will use as few threads as it needs to if you allocate multiple timers, they will share a timing thread) (this from Joe Duffy's Concurrent Programming book)
But more importantly, what are you trying to do? If you are polling -- need to wait for something to happen, you may be able to use a more efficient means of doing it. If you just need to fire off a task every so often, A timer is probably going to be your best bet.
If you are only want to stop for a millisecond, may I ask why? Are you just trying to make sure that your thread yields to other processes?
There may be an alternative way to do this. Windows has a high resolution timer. You can read about it here: "How to: Use the high resolution timer"
I don't think that this works like a regular timer -- it doesn't fire off events, you just use it to measure how much time has passed with high precision. However, you could loop on it, and execute code when a Millisecond passes (you will be consuming CPU the whole time). Also, I agree with Henk's comments that Windows is not a realtime O/S -- you never know when the O/S will suspend your thread.
Related
Please be kind, I'm just learning C# and inheriting this application from a former-employee is my first C# project.
I am observing inconsistent and slow periods with System.Windows.Forms.Timer. The application is written in C# with MS Visual Studio.
The timer is set for an interval of 100 msec yet I am observing periods ranging from 110 msec to 180 msec.
I am using several tools to observe this including:
- a SW oscilloscope (the Iocomp.Instrumentation.Plotting.Plot package),
- a real oscilloscope,
- letting the timer run for some time and comparing the number of ticks * 100 msec to both the system time and to a stopwatch.
In all cases I am observing a 10% lag that becomes evident within the first few seconds.
The methods that are executed with each tick take fewer than 4 msec to run. There is no time-consuming asynchronous processing happening, either. This shouldn't matter, though, as the timer tick is an interrupt, not an event added to an event handler queue (as far as I know).
Has anyone experienced a problem like this before? What were the root causes?
Thanks.
Timers are only as accurate as the operating system clock interrupt. Which ticks 64 times per second by default, 15.625 msec. You cannot get a clean 100 msec interval from that, it isn't divisible by 15.625. You get the next integer multiple, 7 x 15.625 = 109.375 msec. Very close to the 110 msec you observed.
You need to add the latency in the handling of the timer notification to this theoretical minimum. Timers have to compete with everything else that's going on in your UI thread. They are treated as the least important notification to be delivered. Sent messages go first, user input goes next, painting is next, timer messages are last. Either way, if you have an elaborate user interface that takes a while to repaint then the Tick event is going to be delayed until that's done. Same for any event handler you write that does something non-trivial like reading a file or querying a dbase.
To get a more responsive timer that doesn't suffer from this kind of latency, you need to use an asynchronous timer. System.Threading.Timer or System.Timers.Timer. Avoid the latter. Their callback runs on a threadpool thread so can get running pretty quickly. Be very careful what you do in this callback, lots of things you cannot do because they are not thread-safe.
You can these timers more accurate by changing the clock interrupt rate. That requires pinvoke, call timeBeginPeriod(). timeEndPeriod() when you're done.
Yes,I always faced this issue with System.Windows.Forms.Timer as it doesnt ticks accurately(most of the time).
You can try System.Timers.Timer instead and it raises interrupt precisely(atleast for 100ms precision)
System.Windows.Forms.Timer is really just a wrapper for the native WM_TIMER message. this means that the timer message is placed in the message queue at time roughly close to the interval you requested (plus or minus... there's no guarantee here). when that message is processed is entirely dependant on other messages in the queue and how long each takes to process. For example, if you block the UI thread (and thus block the queue from processing new messages) you won't get the timer event until after you unblock.
Windows is not a real-time operating system, you can't expect fine-grained accuracy in timers. If you want something more fine-grained, a multimedia timer is the best choice.
This is old, but in case anyone comes here looking for an actually correct answer:
From https://msdn.microsoft.com/en-us/library/system.windows.forms.timer(v=vs.110).aspx (emphasis mine):
The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.
So with Windows.Forms.Timer you can get 55ms, 110ms, 165ms, etc.; which is consistent with what you were seeing. If you need higher precision, try System.Timers.Timer or System.Threading.Timer
I am using Multimedia timers in my application (C# .NET) to increase accuracy of my timer and to achieve 1 ms timer frequency. My application had been working great so far until recently it started behaving strangely. I am trying to understand what is wrong with my application. Below are the steps taken
timer frequency is set to 1 ms, callback is called on every 1ms
there are 4 threads, each creating its own timer object. They all are set to call the callback after 1ms. These are individual instances and not shared.
old piece of code execution time was about 0.3 ms. This was working fine until next step.
application code is changed. Timer callback function now takes about 1.2 ms for execution. This is clearly a problem. (I am going to work on optimizing the code later. But now I just want to understand the multimedia timer behavior)
only the 1st thread is calling the timer callback where as for other threads the call back is called only twice or thrice and after that the callback is never called.
Looks like for other threads, the timer even is missed (?) and it cannot catch up. (Its missed for every interrupt).
Could you please explain me the behavior of the timer objects. Are all the threads actually pointing to same timer object since its a single process?
Why are other threads not calling the timer callback?
The maximum resolution for the Multimedia timer is 1ms. This causes the programmable interrupt controller (on the hardware) to fire every 1ms. If you fire up 4 threads that all create timers which have 1ms timings that does not mean you will get events more than once per millisecond.
I encourage you to read the Why are the Multimedia Timer APIs (timeSetEvent) not as accurate as I would expect? blog post on MSDN.
Some quotes that are applicable here (emphasis mine):
The MM Timer APIs allow the developer to reprogram the Programmable
Interrupt Controller (PIC) on the machine. You can specify the new
timer resolution. Typically, we will set this to 1 millisecond. This
is the maximum resolution of the timer. We can’t get sub-millisecond
accuracy. The effect of this reprogramming of the PIC is to cause the
OS to wake up more often. This increases the chances that our
application will be notified by the operating system at the time we
specified. I say, “Increases the chances” because we still can’t
guarantee that we will actually receive the notification even though
the OS work up when we told it.
And:
Remember that the PIC is used to wake up the OS so that it can decide
what thread should be run next. The OS uses some very complex rules to
determine what thread gets to occupy the processor next. Two of the
things that the OS looks at to determine if it should run a thread or
not are thread priority and thread quantum.
So, even if you put the resolution down to the maximum of 1ms, you are not guaranteed that your thread will be the one chosen to do its work.
I suppose that you use a system timer that runs callbacks on a single dedicated thread.
Then you set the system interval to 1 ms. And before your change the callback takes 0.3 ms to complete, so the callbacks of the 4 threads take 4 * 0.3 = 1.2 ms to complete. So they manage to complete on 1-2 time intervals, and can all start again after that.
But after your change each callback takes 1.2 ms itself. So we have requests to run callbacks from the threads 2-4 and another request from thread 1 (because the time interval ran out). After that it depends on the timer used, which request it will serve. It turns out, that the one from the first thread.
I wrote some code that mass imports a high volume of users into AD. To refrain from overloading the server, I put a thread.sleep() in the code, executed at every iteration.
Is this a good use of the method, or is there a better alternative (.NET 4.0 applies here)?
Does Thread.Sleep() even aid in performance? What is the cost and performance impact of sleeping a thread?
The Thread.Sleep() method will just put the thread in a pause state for the specified amount of time. I could tell you there are 3 different ways to achieve the same Sleep() calling the method from three different Types. They all have different features. Anyway most important, if you use Sleep() on the main UI thread, it will stop processing messages during that pause and the GUI will look locked. You need to use a BackgroundWorker to run the job you need to sleep.
My opinion is to use the Thread.Sleep() method and just follow my previous advice. In your specific case I guess you'll have no issues. If you put some efforts looking for the same exact topic on SO, I'm sure you'll find much better explanations about what I just summarized before.
If you have no way to receive a feedback from the called service, like it would happen on a typical event driven system (talking in abstract..we could also say callback or any information to understand how the service is affected by your call), the Sleep may be the way to go.
I think that Thread.Sleep is one way to handle this; #cHao is correct that using a timer would allow you to do this in another fashion. Essentially, you're trying to cut down number of commands sent to the AD server over a period of time.
In using timers, you're going to need to devise a way to detect trouble (that's more intuitive than a try/catch). For instance, if your server starts stalling and responding slower, you're going to continue stacking commands that the server can't handle (which may cascade in other errors).
When working with AD I've seen the Domain Controller freak out when too many commands come in (similar to a DOS attack) and bring the server to a crawl or crash. I think by using the sleep method you're creating a manageable and measurable flow.
In this instance, using a thread with a low priority may slow it down, but not to any controllable level. The thread priority will only be a factor on the machine sending the commands, not to the server having to process them.
Hope this helps; cheers!
If what you want is not overload the server you can just reduce the priority of the thread.
Thread.Sleep() do not consume any resources. However, the correct way to do this is set the priority of thread to a value below than Normal: Thread.Current.Priority = ThreadPriority.Lowest for example.
Thread.Sleep is not that "evil, do not do it ever", but maybe (just maybe) the fact that you need to use it reflects some lack on solution design. But this is not a rule at all.
Personally I never find a situation where I have to use Thread.Sleep.
Right now I'm working on an ASP.NET MVC application that uses a background thread to load a lot of data from database into a memory cache and after that write some data to the database.
The only feature I have used to prevent this thread to eat all my webserver and db processors was reduce the thread priority to the Lowest level. That thread will get about to 35 minutes to conclude all the operations instead of 7 minutes if a use a Normal priority thread. By the end of process, thread will have done about 230k selects to the database server, but this do not has affected my database or webserver performance in a perceptive way for the user.
tip: remember to set the priority back to Normal if you are using a thread from ThreadPool.
Here you can read about Thread.Priority:
http://msdn.microsoft.com/en-us/library/system.threading.thread.priority.aspx
Here a good article about why not use Thread.Sleep in production environment:
http://msmvps.com/blogs/peterritchie/archive/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program.aspx
EDIT Like others said here, maybe just reduce your thread priority will not prevent the thread to send a large number of commands/data to AD. Maybe you'll get better results if you rethink all the thing and use timers or something like that. I personally think that reduce priority could resolve your problem, although I think you need to do some tests using your data to see what happens to your server and other servers involved in the process.
You could schedule the thread at BelowNormal priority instead. That said, that could potentially lead to your task never running if something else overloads the server. (Assuming Windows scheduling works the way the documentation on scheduling threads mentions for "some operating systems".)
That said, you said you're moving data into AD. If it's over the nework, it's entirely possible the CPU impact of your code will be negligible compared to I/O and processing on the AD side.
I don't see any issue with it except that during the time you put the thread to sleep then that thread will not be responsive. If that is your main thread then your GUI will become non responsive. If it is a background thread then you won't be able to communicate with it (eg to cancel it). If the time you sleep is short then it shouldn't matter.
I don't think reducing the priority of the thread will help as 1) your code might not even be running on the server and 2) most of the work being done by the server is probably not going to be on your thread anyway.
Thread.sleep does not aid performance (unless your thread has to wait for some resource). It incurs at least some overhead, and the amount of time that you sleep for is not guaranteed. The OS can decide to have your Thread sleep longer than the amount of time you specify.
As such, it would make more sense to do a significant batch of work between calls to Thread.Sleep().
Thread.Sleep() is a CPU-less wait state. Its overhead should be pretty minimal. If execute Thread.Sleep(0), you don't [necessarily] sleep, but you voluntarily surrender your time slice so the scheduler can let lower priority thread run.
You can also lower your thread's priority by setting Thread.Priority.
Another way of throttling your task is to use a Timer:
// instantiate a timer that 'ticks' 10 times per second (your ideal rate might be different)
Timer timer = new Timer( ImportUserIntoActiveDirectory , null , 0 , 100 ) ;
where ImportUserIntoActiveDirectory is an event handler that will import just user into AD:
private void ImportUserIntoActiveDirectory( object state )
{
// import just one user into AD
return
}
This lets you dial things in. The event handler is called on thread pool worker threads, so you don't tie up your primary thread. Let the OS do the work for you: all you do is decide on your target transaction rate.
Right now, I'm reading outside application's memory in a new thread with a infinte loop
public void ReadMemory()
{
//read memory
Thread.Sleep(10);
}
Unfortunately, with even sleep of 1 ms, I can get 60-100 loops during 1 minute. Without any sleep, it's 1000-1500/sec loops but it takes much CPU. I can't believe there's nothing I can do with that so Im asking you here :P. CPU usage might be a problem because I'd like to add few more background-working functions in a different threads(or smth else)
is there anything that doesn't decrease ammount of loops like that with a pause of 10 ms?
Don't worry about CPU usage. It's a nonsensical concept.
There's no such thing as "code that runs a little bit", or "running code slowly to only consume 25% CPU".
At the lowest level, it's a binary thing: your code either runs, consuming 100% of the core it runs on, or it doesn't, in which case it uses 0% CPU.
The CPU usage that the OS shows you is a running average.
So the question you need to ask is not "how do I run my code without using so much CPU", but the much simpler "does my code run when it shouldn't be running?" If you want your code to run, then it will, temporarily, at least, use 100% CPU, and there's nothing wrong with that.
It's not really clear what role the Sleep() call plays in your application.
What are you waiting for? Do you just want a few milliseconds to pass between each iteration? Or are you waiting for some specific event to occur?
In any case, when you call Sleep(10), you are not suspending your thread for 10 milliseconds. You are suspending it for at least 10 milliseconds. You're telling the OS to put the thread into a sleep queue now, and once 10 ms have passed, the thread should be considered eligible to execute again. But that still depends on the OS getting around to scheduling your thread, which might take another 10ms (or more, or less, depending on a variety of factors)
On Windows, Sleep(0) is a special case, which you could experiment with. Instead of actually suspending your thread, it simply tells the OS that the thread is done with its current timeslice, allowing other threads/processes to execute, but without putting your thread to sleep: it's still eligible to be scheduled the next time a context switch occurs.
So if the goal is simply to ensure that other threads/processes get a chance to run, calling Sleep(0) might be a way to do it.
Another way is just to ignore the issue, and trust that the OS knows how to schedule processes (that is a pretty safe assumption. Don't worry about this unless you've actually seen that your other background processes are being starved. They most likely won't be).
And finally, of course, you can set thread and process priority, hinting to the OS at which threads it should prefer to schedule. If you give this thread a low priority, it will only be scheduled when no higher-prioritized thread is available, ensuring you won't starve out other threads.
Threads are designed to consume as much CPU time as they can, unless other threads need that CPU time. If you're just trying to release the thread so that the CPU can do other tasks, don't. Windows will automatically allocate horsepower to any other threads, as needed.
Rather than sleeping every iteration, what if you only do it occasionally.
Something like :
public class Reader
{
private static int count= 0;
public void ReadMemory()
{
//read memory
// Sleep every 501 iterations
if (Reader.count++ == 500)
{
Thread.Sleep(1);
Reader.count = 0;
}
}
}
If you are running at about 1000 iterations a second and it takes 1 second to perform the switch then this will mean you will be running at full power for half-a-second, then throttle back for a second and then back to full power which will average out at 333 iterations per second.
Obviously you can try experimenting with values other than 500.
I have a Winform which needs to wait for about 3 - 4 hours. I can't close and somehow reopen the App, as it does few things in background, while it waits.
To achieve the wait - without causing trouble to the UI thread and for other reasons -, I have a BackgroundWorker to which I send how many milliseconds to wait and Call Thread.Sleep(waitTime); in its doWork event. In the backGroundWorker_RunWorkerCompleted event, I do what the program is supposed to do after the wait.
This works fine on the development machine. i.e. the wait ends when it has to end. But on the Test machine, it keeps waiting for longer. It happened two times, first time it waited exactly 1 hour more than specified time and second time it waited more for about 2 Hours and 40 minutes.
Could there be any obvious reason for this to happen or am I missing something?
The dev machine is Win XP and Test machine is Win 7.
I propose to use ManualResetEvent instead:
http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx
ManualResetEvent mre = new ManualResetEvent(false);
mre.WaitOne(waitTime);
...
//your background worker process
mre.Set();
As a bonus you will have an ability to interrupt this sleep quicker.
Have a look at this article which explains the reason:
Thread.Sleep(n) means block the current thread for at least the number
of timeslices (or thread quantums) that can occur within n
milliseconds. The length of a timeslice is different on different
versions/types of Windows and different processors and generally
ranges from 15 to 30 milliseconds. This means the thread is almost
guaranteed to block for more than n milliseconds. The likelihood that
your thread will re-awaken exactly after n milliseconds is about as
impossible as impossible can be. So, Thread.Sleep is pointless for
timing.
By the way it also explains why not to use Thread.Sleep ;)
I agree to the other recommendations to use a Timer instead of the Thread.Sleep.
In my humble opinion, the difference in wait time cannot solely be explained by the information that you have given us. I would really think that the cause of the difference lies within the moment of starting the sleep. So the actual Thread.sleep(waitTime); call. Are you sure that the sleep is called at the moment you think it is?
And, as suggested by the comment, if you really need to wait for this long; consider using a Timer to start the events needed. Or even scheduling of some sort, within your application. Of course, this depends on your actual implementation and thus can be easier said than done. But it 'feels' silly, letting a BackgroundWorker sleep for so long.
PREFIX: This requires .NET 4 or newer
Consider making your function async and simply doing:
await Task.Delay(waitTime);
Alternately, if you can't make your function async (or don't want to) you could also do:
Task.Delay(waitTime).Wait();
This is a one-line solution and anyone with a copy of Reflector can verify that Task.Delay uses a timer internally.