简体   繁体   English

无法触发事件(计时器)

[英]not able to fire event (timer)

I have a function in winform that is executed every x time (eg. every 60 minutes). 我在winform中有一个函数,该函数每x次执行一次(例如,每60分钟执行一次)。
And then it does some stuff, then I want it to wait some seconds (using a timer) and then execute do some stuff part2. 然后执行一些操作,然后我希望它等待几秒钟(使用计时器),然后执行第二部分的操作。

 private void goToFtp(int time)
        { 
            double interval = time* 60 * 1000;
            System.Timers.Timer checkForTime = new System.Timers.Timer(interval);
            checkForTime.Elapsed += new ElapsedEventHandler(checkForTime_Elapsed);
            checkForTime.Enabled = true;
        }



    System.Windows.Forms.Timer timerDelayWatcher = new System.Windows.Forms.Timer();

    private void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
        {

         .......Do some stuff part1

            timerDelayWatcher.Tick += new EventHandler(timerDelayWatcher_Tick); // Everytime timer ticks, timer_Tick will be called
            timerDelayWatcher.Interval = (1000) * (5);              
            timerDelayWatcher.Enabled = true;                       
            timerDelayWatcher.Start();
        }


            private void timerDelayWatcher_Tick(object sender, EventArgs e)
        {

            timerDelayWatcher.Stop();

                .......Do some stuff part2

        }

The problem is that the timerDelayWatcher_Tick is not fired...any ideias why? 问题是没有触发timerDelayWatcher_Tick ...任何想法为何?

Try calling the start method on the system.timers.timer firstly, and I would recommend sticking to one type of timer, and pattern of use, say use the system.timer.timer and do the work you need on elapsed, then restart with and wait for the next elapsed event. 首先尝试在system.timers.timer上调用start方法,我建议坚持使用一种类型的计时器和使用方式,比如说使用system.timer.timer并完成您需要的工作,然后重新启动并等待下一个过去的事件。

Either that or I would suggest looking at the task library and async flow in .net 4/4.5 and as @Ferri suggests using a Sleep 要么,要么我建议查看.net 4 / 4.5中的任务库和异步流,就像@Ferri建议使用Sleep一样

You need use: 您需要使用:

Thread.Sleep(5000);

But first you need add 但首先您需要添加

using System.Threading;

or use 或使用

System.Threading.Thread.Sleep(5000);

on 5000 are the time in milliseconds 5000上的时间以毫秒为单位

Sample 样品

private void timerDelayWatcher_Tick(object sender, EventArgs e)
    {

        timerDelayWatcher.Stop();

        System.Threading.Thread.Sleep(5000);

            .......Do some stuff part2

    }

Take also care on loosing reference to the class containing the timerDelayWatcher member. 在丢失对包含timerDelayWatcher成员的类的引用时也要格外小心。 If it happens the timer is disposed so no more events... 如果发生这种情况,计时器将被处理,因此不再有事件...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM