定时器启动时调用 Tick 事件 [英] call Tick event when timer starts

查看:36
本文介绍了定时器启动时调用 Tick 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用System.Windows.Forms.Timer"来重复一项任务.但是当计时器启动时,我必须等待一个时间间隔才能开始任务.间隔设置为 10 秒,以便为任务提供足够的时间来完成它的工作.但是有一种尴尬的沉默"等待它第一次开始.有没有办法在定时器启用时触发 Tick 事件?(我无法使用线程、回调或事件来使任务重复)

I'm using 'System.Windows.Forms.Timer' to repeat a task. But when the timer starts, I have to wait for one interval before the task starts. The interval is set to 10 seconds to give the task enough time to do it's thing. But there is an 'awkward silence' waiting for it to start the first time. Is there a way to trigger the Tick event when the timer is enabled? (I am unable to use threading, callbacks or events to get the task repeat)

private int counter;
Timer t = new Timer();

private void InitializeTimer()
{
    counter = 0;
    t.Interval = 750;
    t.Enabled = true;

    t.Tick += new EventHandler(timer1_Tick);
}

private void timer1_Tick(object sender, EventArgs e)
{
    if (counter >= 3)
    {
        t.Enabled = false;                
    }
    else
    {
        //do something here
        counter++;
    }
}

推荐答案

您始终可以手动调用您的方法:

You can always call your method manually:

private void InitializeTimer()
{
    counter = 0;
    t.Interval = 750;
    t.Enabled = true;
    timer1_Tick(null, null);

    t.Tick += new EventHandler(timer1_Tick);
}

这篇关于定时器启动时调用 Tick 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆