在我正在开发的VSTO外接程序中,我需要以特定的延迟执行一个方法。棘手的部分是,该方法的执行时间可能在0.1秒到1秒之间。我目前使用的System.Timers.Timer是这样的:
private Timer tmrRecalc = new Timer();
// tmrRecalc.Interval = 500 milliseconds
private 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();
}它基本上启动,引发一个elapse事件,之后它被停止,因为执行任意长度的任务。但UI线程似乎会在每个任务之间挂起3-5秒。
计时器有“热身”时间开始吗?这就是为什么它花了这么长时间才第一次(也是最后一次)过去?
我应该使用哪种类型的计时器?
发布于 2010-03-24 08:07:56
与使用计时器相比,我建议在不同的线程(生成线程)中进行计算,并使用Thread.Sleep(milliseconds)在间隔之间休眠。这对我来说非常有效。
发布于 2010-03-24 08:04:29
也许你的计算花费的时间比你想象的要长。计时器没有任何形式的热身。
有没有什么原因你不能使用后台线程,也许是BackgroundWorker对象来运行计算,而不需要计时器?
https://stackoverflow.com/questions/2504483
复制相似问题