In a VSTO add-in I'm developing, I need to execute a method with a specific delay. The tricky part is that the method may take anywhere from 0.1 sec to 1 sec to execute. I'm currently using a System.Timers.Timer
like this:
private Timer tmrRecalc = new Timer();
// tmrRecalc.Interval = 500 milliseconds
priv开发者_JAVA百科ate void tmrRecalc_Elapsed(object sender, System.Timers.ElapsedEventArgs e){
// stop the timer, do the task
tmrRecalc.Stop();
Calc.recalcAll();
// restart the timer to repeat after 500 ms
tmrRecalc.Start();
}
Which basically starts, raises 1 elapse event after which it is stopped for the arbitrary length task is executed. But the UI thread seems to hang up for 3-5 seconds between each task.
Do Timers have a 'warm-up' time to start? Is that why it takes so long for its first (and last) elapse?
Which type of timer do I use instead?
Instead of using a timer I recommend doing the calculations in a different thread (spawn a thread), and using Thread.Sleep(milliseconds) to sleep between intervals. This has worked quite wonderfully for me.
Maybe your calculations are taking longer than you thought. Timers don't have any kind of warm-up.
Is there any reason you can't use a background thread, maybe a BackgroundWorker object to run the calculations without needing a timer?
精彩评论