Question

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 ;) )?

Was it helpful?

Solution

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).

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top