Are there any classes in the .NET framework I can use to throw an event if time has caught up with a specified DateTime object?
If there isn't, what are the best practices when checking this? Create a new thread constantly checking? A timer (heaven forbid ;) )?
I wouldn't go with the thread approach. While a sleeping thread doesn't consume user CPU time, it does use Kernel/system CPU time. Secondly, in .NET you can't adjust the Thread's stack size. So even if all it does is sleep, you are stuck with a 2MB hit (I believe that is the default stack size of a new thread) for nothing.
Using System.Threading.Timer. It uses an efficient timer queue. It can have hundreds of timers that are lightweight and only execute on 1 thread that is reused between all timers (assuming most timers aren't firing at the same time).
When a thread is sleeping it consumes no CPU usage. A very simple way would be to have a thread which sleeps until the DateTime. For example
DateTime future = DateTime.Now.Add(TimeSpan.FromSeconds(30));
new Thread(() =>
{
Thread.Sleep(future - DateTime.Now);
//RaiseEvent();
}).Start();
This basically says, get a date in the future (thirty seconds from now). Then create a thread which will sleep for the difference of the times. Then raise your event.
Edit: Adding some more info about timers. There is nothing wrong with timers, but I think it might be more work. You could have a timer with an interval of the difference between the times. This will cause the tick event to fire when the time has caught up to the date time object.
An alternative, which I would not recommend, and I seem to think you have though of this, is to have a timer go off every five seconds and check to see if the times match. I would avoid that approach and stick with having the thread sleep until there is work to be done.
A timer is probably not a bad way to go. Just use DateTime.Now to detect if it's over the target time. Don't use == unless you try to normalize the times to the minute or the hour or something.
Related
I'm working with a timeout which is set to occur after a certain elapsed period, after which I would like to get a callback. Right now I am doing this using a Timer that when fired disposes of itself.
public class Timeouter
{
public void CreateTimeout(int timeout, Action onTimeout)
{
Timer t = null;
t = new Timer(_ =>
{
onTimeout();
t.Dispose();
}, new object(), timeout, Timeout.Infinite);
}
}
I'm a bit concerned regarding the resource use of this timer since it could potentially be called quite frequently and would thus setup a lot of timers to fire just once and dispose of themselves. Considering that the timer is an IDisposable it would indicate to me that it indeed uses some sort of expensive resource to accomplish its task.
Am I worrying too much about the resource usage of the Timer, or perhaps the solution is fine as it is?
Do I have any other options for doing this? Would it be better to have a single timer and fiddling with it's frequency starting and stopping it as necessary in order to accommodate several of these timeouts? Any other potentially more lightweight option to have a task execute once after a given period of time has elapsed?
.Net has 2 or 3 timer classes which are expensive. However the System.Threading.Timer class which you're using is a very cheap one. This class do not use kernel resources or put a thread to sleep waiting for timeout. Instead it uses only one thread for all Timer instances, so you can easily have thousands of timers and still get a tiny processor and memory footprint. You must call Dispose only because you must notify the system to stop tracking some timer instance, but this do not implies that this is a expensive class/task at all.
Once the timeout is reached this class will schedule the callback to be executed by a ThreadPool thread, so it do not start a new thread or something like this.
Though its not an answer, but due to length I added it as answer.
In a server/Client environment, AFAIK using Timers on server is not the best approach, rather if you have thick clients or even thin clients, you should devise some polling mechanism on client if it wants a certain operation to be performed on the server for itself(Since a client can potentially disconnect after setting up a timer and then reinstantiate and set a timer again an so on, causing your server to be unavailable at sometime in future(a potential DOS attack)),
or else think of a single timer strategy to deal with all clients, which implements sliding expirations or client specific strategies to deal with it.
one other option is to maintain a sorted list of things which will timeout, add them to the list with their expiry time instead of their duration, keep the list sorted by the expiry time and then just pop the first item off the list when it expires.
You will of course need to most of this on a secondary thread and invoke your callbacks. You don't actaully need to keep the thread spinning either, you could set a wait handle on the add method with a timeout set for (a bit less than) the duration until the next timeout is due. See here for more information on waiting with a timeout.
I don't know if this would be better than creating lots of timers.
Creating a cheap timer that can time many intervals is intuitively simple. You only need one timer. Set it up for the closest due time. When it ticks, fire the callback or event for every timer that was due. Then just repeat, looking again through the list of active timers for the next due time. If a timer changes its interval then just repeat the search again.
Something potentially expensive might happen in the callback. Best way to deal with that is to run that code on a threadpool thread.
That's extraordinarily frugal use of system resources, just one timer and the cheapest possible threads. You pay for that with a little overhead whenever a timer's state changes, O(n) complexity to look through the list of active timers, you can make most of it O(log(n)) with a SortedList. But the Oh is very small.
You can easily write that code yourself.
But you don't have to, System.Timers.Timer already works that way. Don't help.
in my application I have an "heartbeat" functionality that is currently implemented in a long running thread in the following way (pseudocode):
while (shouldBeRunning)
{
Thread.Sleep(smallInterval);
if (DateTime.UtcNow - lastHeartbeat > heartbeatInterval)
{
sendHeartbeat();
lastHeartbeat = DateTime.UtcNow;
}
}
Now, it happens that when my application is going through some intensive CPU time (several minutes of heavy calculations in which the CPU is > 90% occupied), the heartbeats get delayed, even if smallInterval << heartbeatInterval.
To crunch some numbers: heartbeatInterval is 60 seconds, lastHeartbeat is 0.1 seconds and the reported delay can be up to 15s. So, in my understanding, that means that a Sleep(10) can last like a Sleep(15000) when the CPU is very busy.
I have already tried setting the thread priority as AboveNormal - how can I improve my design to avoid such problems?
Is there any reason you can't use a Timer for this? There are three sorts you can use and I usually go for System.Timers.Timer. The following article discusses the differences though:
http://msdn.microsoft.com/en-us/magazine/cc164015.aspx
Essentially timers will allow you to set up a timer with a periodic interval and fire an event whenever that period ticks past. You can then subscribe to the event with a delegate that calls sendHeartbeat().
Timers should serve you better since they won't be affected by the CPU load in the same way as your sleeping thread. It has the advantage of being a bit neater in terms of code (the timer set up is very simple and readable) and you won't have a spare thread lying around.
You seem to be trying to reinvent one of the timer classes.
How about using System.Timers.Timer for example?
var timer = new System.Timers.Timer(smallInterval);
timer.Elapsed += (s, a) => sendHeartbeat;
timer.Enabled = true;
One of the issues here may be, at a guess, how often your thread gets scheduled when the CPU is under load. Your timer implementation is inherently single threaded and blocks. A move to one of the framework timers should alleviate this as (taking the above timer as an example) the elapsed event is raised on a thread pool thread, of which there are many.
Unfortunately, Windows is not a Real Time OS and so there are few guarantees about when threads are executed. The Thread.Sleep () only schedules the earliest time when the thread should be woken up next, it is up to the OS to wake up the thread when there's a free time slice. The exact criteria for waking up a sleeping thread is probably not documented so that the Window's kernel team can change the implementation as they see fit.
I'm not sure that Timer objects will solve this as the heartbeat thread still needs to be activated after the timer has expired.
One solution is to elevate the priority of the heartbeat thread so that it gets a chance of executing more often.
However, heartbeats are usually used to determine if a sub-system has got stuck in an infinite loop for example, so they are generally low priority. When you have a CPU intensive section, do a Thread.Sleep (0) at key points to allow lower priority threads a chance to execute.
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.
Is there relialbe alternative to Timer class in .Net?
We are having issues with System.Timers.Timer and System.Threading.Timer, e.g., they start immidietly, or sometimes fire out after long period of inactivity (after 49 days).
I've seen that there seems to be a lot of issues with them like here: http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/dbc398a9-74c0-422d-89ba-4e9f2499a6a3
We can not use Forms timer.
We are thinking to pause the thread for certain period of time instead of the timer...
This article describes the difference between the timer classes in the .Net framework.
But maybe another approach can help:
If have have to wait for such a long time it would be better to calculate the DateTime when you like something to start. Afterwards your task wakes up every second (or whatever accuracy is needed) and compares the current time with the desired time. If the current time is equal or greater just start your job. Otherwise go to sleep (till the next second, hour, millisecond, whatever). By the way, that's the way how the Microsoft Task Scheduler works.
I think you need System.Diagnostics.Stopwatch.
The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.
You could replace the timer with a new instance every 48 days in the Tick/Elapsed event handler.
The threading will most likely work, but is it going to be worth the extra overhead?
I'm also aware of those limitations and have implemented an own timer. Sucked to take that decision, but I have not regretted it so far. As a bonus my own timer implements an interface so that classes using the timer can be unit-tested easily.
Some .NET timers also has a problem where they may invoke the callback before the last callback has finished.
I would recommend putting the timer logic in it's own class rather than pausing a thread.
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.