C#定时器事件未启动

时间:2015-01-20 10:22:37

标签: c# events timer

每当我创建一个新的命令对象时,我都无法让计时器打勾。我想知道是什么导致了这个问题。我是C#的新手,所以如果我能得到帮助,为什么会发生这种情况,我将不胜感激。

这应该触发,但不会

command Cmd = new command("!example", 10);

这是代码。

public class Timeout
{
    public Timeout() { }
    public static List<command> timeouts = new List<command>();
    public class command
    {
        public string cmd;
        public int seconds;
        private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer() { Interval = 1000 };
        public command(string cmd, int seconds)
        {
            Debug.WriteLine("created, " + cmd + ", " + seconds);
            this.cmd = cmd;
            this.seconds = seconds;
            this.timer.Tick += new EventHandler(Timer_Tick);           
            timer.Start();
        }
        private void Timer_Tick(object sender, EventArgs e)
        {
            Debug.WriteLine("tick -> " + seconds);
            if (seconds > 0)
                seconds--;
            else
            {
                timer.Tick -= Timer_Tick;
                timeouts.Remove(this);
                Debug.WriteLine("removed");
            }                   
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

实际上你可以这样做。 创建对象后调用计时器

command cmd =new command("!example",10);
//then am calling the timer event
timer = new Timer(3000); // Set up the timer for 3 seconds
timer.Elapsed += new ElapsedEventHandler(timerElapsed);
//_timer_Elapsed is the event name
timer.Enabled = true;

public static void timerElapsed(object sender, ElapsedEventArgs e)
{
//do something here
}

请找到here链接以获取更多参考。我的评论可以帮助您:)