如何在滴答数之后或在3-4秒之后停止计时器?
因此,我启动一个计时器,我希望在10滴答或2-3秒后自动停止。
谢谢!
发布于 2013-08-07 10:10:40
你可以保留一个柜台
int counter = 0;然后,在每一个滴答,你增加它。在你的限制之后,你可以停止计时器。在您的滴答事件中这样做。
counter++;
if(counter ==10) //or whatever your limit is
yourtimer.Stop();发布于 2013-08-07 10:18:06
当达到定时器指定的间隔(3秒后)时,将调用timer1_Tick()事件处理程序,您可以在事件处理程序中停止定时器。
Timer timer1 = new Timer();
timer1.Interval = 3000;
timer1.Enabled = true;
timer1.Tick += new System.EventHandler(timer1_Tick);
void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop(); // or timer1.Enabled = false;
}发布于 2013-08-07 10:12:27
假设您使用的是System.Windows.Forms.Tick。你可以跟踪一个柜台,它的生活时间是这样的。使用计时器的标记属性是一种很好的方法。这使得它对其他定时器可重用,并保持代码的通用性,而不是对每个定时器使用全局定义的int counter。
此代码是安静的通用代码,因为您可以分配此事件处理程序来管理它的生存期,并分配另一个事件处理程序来处理为定时器创建的特定操作。
System.Windows.Forms.Timer ExampleTimer = new System.Windows.Forms.Timer();
ExampleTimer.Tag = new CustomTimerStruct
{
Counter = 0,
StartDateTime = DateTime.Now,
MaximumSecondsToLive = 10,
MaximumTicksToLive = 4
};
//Note the order of assigning the handlers. As this is the order they are executed.
ExampleTimer.Tick += Generic_Tick;
ExampleTimer.Tick += Work_Tick;
ExampleTimer.Interval = 1;
ExampleTimer.Start();
public struct CustomTimerStruct
{
public uint Counter;
public DateTime StartDateTime;
public uint MaximumSecondsToLive;
public uint MaximumTicksToLive;
}
void Generic_Tick(object sender, EventArgs e)
{
System.Windows.Forms.Timer thisTimer = sender as System.Windows.Forms.Timer;
CustomTimerStruct TimerInfo = (CustomTimerStruct)thisTimer.Tag;
TimerInfo.Counter++;
//Stop the timer based on its number of ticks
if (TimerInfo.Counter > TimerInfo.MaximumTicksToLive) thisTimer.Stop();
//Stops the timer based on the time its alive
if (DateTime.Now.Subtract(TimerInfo.StartDateTime).TotalSeconds > TimerInfo.MaximumSecondsToLive) thisTimer.Stop();
}
void Work_Tick(object sender, EventArgs e)
{
//Do work specifically for this timer
}https://stackoverflow.com/questions/18100524
复制相似问题