System.Windows.Forms.Timer不会触发Foreach Block内的Tick事件

时间:2014-02-28 16:31:44

标签: c# winforms timer

我有一个与我的主窗体关联的System.Windows.Forms.Timer。我需要这个计时器每1000ms启动一次,以便可以执行一些工作。在Form.Shown事件中,Timer.Enabled属性设置为true,并且间隔设置为1000.

Timer.Tick事件大部分都会触发每秒。但是,当我的应用程序执行foreach语句时,Tick事件将停止触发。我试过Thread.Sleep但是,这没有帮助。有没有人有什么建议?处理我的Timer.Tick事件的代码包含异常处理,我已经验证在foreach块执行期间事件在调试器中停止触发。另外,我的应用程序目前不是多线程的。有什么建议吗?

2 个答案:

答案 0 :(得分:4)

如果您在循环中保持UI线程忙,那么不会,定时器Tick处理程序将无法执行。如果您有一个长时间运行的循环,请将其推送到后台线程。睡眠无济于事,因为它也会阻止UI线程。还有其他计时器不会在UI线程(System.Timer)上触发,但如果您的tick需要访问UI,那么如果UI线程仍然忙碌,那么这实际上对您没有帮助。

答案 1 :(得分:1)

System.Timers.Timer的实现可能如下所示:

var timer = new System.Timers.Timer();
timer.Interval = 1000; // every second
timer.Elapsed += TimerTick;

...

private void TimerTick(object state, System.Timers.ElapsedEventArgs e)
{
    // do some work here
    Thread.Sleep(500);

    var reportProgress = new Action(() => 
    {  
        // inside this anonymous delegate, we can do all the UI updates
        label1.Text += string.Format("Work done {0}\n", DateTime.Now);
    });
    Invoke(reportProgress);
}
相关问题