C#计时器自动停止一些滴答后停止
如何在经过一些滴答或之后停止计时器,比方说3-4秒?
所以我启动一个计时器,我希望在10个滴答之后或2-3秒后自动停止。
谢谢!
你可以保持一个柜台
int counter = 0;
然后在每个刻度线中增加它。 在你的限制后你可以停止计时器。 在您的tick事件中执行此操作
counter++; if(counter ==10) //or whatever your limit is yourtimer.Stop();
当达到计时器的指定间隔时(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; }
我一般都在说话,因为你没有提到哪个计时器,但它们都有刻度…所以:
你需要class上的一个柜台,比如
int count;
您将在计时器的开头初始化,并且您需要一个dateTime
DateTime start;
您将在计时器的开头初始化:
start = DateTime.Now;
在你的滴答方法中你会做:
if(count++ == 10 || (DateTime.Now - start).TotalSeconds > 2) timer.stop()
这是一个完整的例子
public partial class meClass : Form { private System.Windows.Forms.Timer t; private int count; private DateTime start; public meClass() { t = new Timer(); t.Interval = 50; t.Tick += new EventHandler(t_Tick); count = 0; start = DateTime.Now; t.Start(); } void t_Tick(object sender, EventArgs e) { if (count++ >= 10 || (DateTime.Now - start).TotalSeconds > 10) { t.Stop(); } // do your stuff } }
假设您正在使用System.Windows.Forms.Tick
。 你可以跟踪一个柜台,以及它的生存时间。 它是一种使用计时器的Tag属性的好方法。 这使得它可以重用于其他计时器并保持代码通用,而不是为每个计时器使用全局定义的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 }
初始化计时器时,将标记值设置为0(零)。
tmrAutoStop.Tag = 0;
然后,每个滴答添加一个……
tmrAutoStop.Tag = int.Parse(tmrAutoStop.Tag.ToString()) + 1;
并检查它是否达到了您想要的数字:
if (int.Parse(tmrAutoStop.Tag.ToString()) >= 10) { //do timer cleanup }
使用相同的技术来交替计时器相关事件:
if (int.Parse(tmrAutoStop.Tag.ToString()) % 2 == 0) { //do something... } else { //do something else... }
要检查已用时间(以秒为单位):
int m = int.Parse(tmrAutoStop.Tag.ToString()) * (1000 / tmrAutoStop.Interval);