In .NET, does WaitHandle.WaitOne(int millisecondsTimeout) (and presumably methods that block with timeouts, such as Thread.Sleep()) include time that the computer is hibernating or sleeping? For example, if I call WaitHandle.WaitOne(600000) to timeout in ten minutes, the computer hibernates for 5 of those minutes, will it timeout 10 minutes after calling or 15 minutes after calling?
My goal is to have it not include time spent during hibernation or sleeping.
Since Windows 7, kernel32.dll has a QueryUnbiasedInterruptTime function.
The unbiased interrupt-time count does not include time the system spends in sleep or hibernation.
The remarks provide pretty conclusive evidence that ordinary waits and timers do count time spent suspended:
The interrupt-time count retrieved by the QueryUnbiasedInterruptTime function reflects only the time that the system is in the working state. Therefore, the interrupt-time count is not "biased" by time the system spends in sleep or hibernation. The system uses biased interrupt time for some operations, such as ensuring that relative timers that would have expired during sleep expire immediately upon waking.
You will probably need p/invoke to call it from C# since I've never heard of any .NET base class library approach to doing it.
It doesn't put your thread to sleep by itself, you'll have to call it before and after the synchronizing sleep and calculate how much sleep time you still need (in case you lost some due to power savings) and then return to sleep again with the new timeout. Repeat in a loop until you actually sleep for as much CPU time as desired.
If you're using async code, there's no reason you couldn't use this function also for recalibration of Task.Delay, which you call in a loop. CancellationTokenSource.CancelAfter is a bit more problematic, since you can't uncancel if your calculation reveals you need to adjust the timeout. So you'd have to separately sleep and cancel the token yourself, without the help of scheduled cancellation.
Finally, if you're trying to set a timeout to happen after some other process has had a chance to do a certain amount of work, regardless of the passage of wall-clock time, you should be using resource limits on a Job object. The Job object measures CPU time actually spent by a particular process and is unaffected by time the process isn't working, whether due to suspend, being preempted by higher priority tasks, etc.
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.
In C#.NET, is there a way to measure the actual CPU time of a thread/task. This time should NOT include the blocking/preemption time. I know that a StopWatch can be used to measure the total time for a task from start to finish, but this will also include the blocking time. Is there a way to exclude the blocking time?
System.Diagnostics.ProcessThread.TotalProcessorTime will give you the amount of CPU time that a given thread has consumed.
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 queue of tasks for the ThreadPool, and each task has a tendency to froze locking up all the resources it is using. And these cant be released unless the service is restarted.
Is there a way in the ThreadPool to know that its thread is already frozen? I have an idea of using a time out, (though i still dont know how to write it), but i think its not safe because the length of time for processing is not uniform.
I don't want to be too presumptuous here, but a good dose of actually finding out what the problem is and fixing it is the best course with deadlocks.
Run a debug version of your service and wait until it deadlocks. It will stay deadlocked as this is a wonderful property of deadlocks.
Attach the Visual Studio debugger to the service.
"Break All".
Bring up your threads windows, and start spelunking...
Unless you have a sound architecture\design\reason to choose victims in the first place, don't do it - period. It's pretty much a recipe for disaster to arbitrarily bash threads over the head when they're in the middle of something.
(This is perhaps a bit lowlevel, but at least it is a simple solution. As I don't know C#'s API, this is a general solution for any language using thread-pools.)
Insert a watchdog task after each real task that updates a time value with the current time. If this value is larger than you max task run time (say 10 seconds), you know that something is stuck.
Instead of setting a time and polling it, you could continuously set and reset some timers 10 secs into the future. When it triggers, a task has hung.
The best way is probably to wrap each task in a "Watchdog" Task class that does this automatically. That way, upon completion, you'd clear the timer, and you could also set a per-task timeout, which might be useful.
You obviously need one time/timer object for each thread in the threadpool, but that's solvable via thread-local variables.
Note that this solution does not require you to modify your tasks' code. It only modifies the code putting tasks into the pool.
One way is to use a watchdog timer (a solution usually done in hardware but applicable to software as well).
Have each thread set a thread-specific value to 1 at least once every five seconds (for example).
Then your watchdog timer wakes every ten seconds (again, this is an example figure only) and checks to ensure that all the values are 1. If they're not 1, then a thread has locked up.
The watchdog timer then sets them all to 0 and goes back to sleep for the next cycle.
Providing your worker threads are written in such a way so that they will be able to set the values in a timely manner under non-frozen conditions, this scheme will work okay.
The first thread that locks up will not set its value to 1, and this will be detected by the watchdog timer on the next cycle.
However, a better solution is to find out why the threads are freezing in the first place and fix that.