C# 定时器事件没有触发
C# Timer Event not firing off
我每次创建新的命令对象时都无法让计时器计时我想知道是什么原因造成的。我是 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");
}
}
}
}
实际上你可以这样做。
创建对象后调用计时器
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
}
更多请找linkherereference.hope我的评论对你有帮助:)
我每次创建新的命令对象时都无法让计时器计时我想知道是什么原因造成的。我是 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");
}
}
}
}
实际上你可以这样做。 创建对象后调用计时器
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
}
更多请找linkherereference.hope我的评论对你有帮助:)