C# 计时器在一定数量的滴答后自动停止

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18100524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:17:11  来源:igfitidea点击:

C# timer stop after some number of ticks automatically

c#winformstimer

提问by Razvan Ghena

How to stop a timer after some numbers of ticks or after, let's say, 3-4 seconds?

如何在一定数量的滴答声或之后(比方说 3-4 秒)停止计时器?

So I start a timer and I want after 10 ticks or after 2-3 seconds to stop automatically.

所以我启动了一个计时器,我想在 10 个滴答声或 2-3 秒后自动停止。

Thanks!

谢谢!

采纳答案by Ehsan

You can keep a counter like

你可以保留一个计数器

 int counter = 0;

then in every tick you increment it. After your limit you can stop timer then. Do this in your tick event

然后在每个刻度中你增加它。在您的限制之后,您可以停止计时器。在您的滴答事件中执行此操作

 counter++;
 if(counter ==10)  //or whatever your limit is
   yourtimer.Stop();

回答by Mike de Klerk

Assuming you are using the System.Windows.Forms.Tick. You can keep track of a counter, and the time it lives like so. Its a nice way to use the Tag property of a timer. This makes it reusable for other timers and keeps your code generic, instead of using a globally defined int counterfor each timer.

假设您正在使用System.Windows.Forms.Tick. 你可以跟踪一个计数器,以及它的存在时间。这是使用计时器的 Tag 属性的好方法。这使它可重用于其他计时器并保持您的代码通用,而不是使用int counter为每个计时器全局定义的。

this code is quiet generic as you can assign this event handler to manage the time it lives, and another event handler to handle the specific actions the timer was created for.

此代码是安静的通用代码,因为您可以分配此事件处理程序来管理它的生存时间,并分配另一个事件处理程序来处理创建计时器的特定操作。

    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
    }

回答by No Idea For Name

i generally talking because you didn't mention which timer, but they all have ticks... so:

我通常在说话是因为你没有提到哪个计时器,但它们都有刻度......所以:

you'll need a counter in the class like

你需要在课堂上有一个计数器,比如

int count;

which you'll initialize in the start of your timer, and you'll need a dateTime like

您将在计时器开始时对其进行初始化,并且您需要一个 dateTime 之类的

DateTime start;

which you'll initialize in the start of your timer:

您将在计时器开始时初始化:

start = DateTime.Now;

and in your tick method you'll do:

并在您的滴答方法中,您将执行以下操作:

if(count++ == 10 || (DateTime.Now - start).TotalSeconds > 2)
   timer.stop()

here is a full example

这是一个完整的例子

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
  }
}

回答by beastieboy

When the timer's specified interval is reached (after 3 seconds), timer1_Tick()event handler will be called and you could stop the timer within the event handler.

当达到计时器的指定间隔时(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;
}

回答by Sam Saarian

When initializing your timer set a tag value to 0 (zero).

初始化计时器时,将标记值设置为 0(零)。

tmrAutoStop.Tag = 0;

Then, with every tick add one...

然后,每滴答加一个...

tmrAutoStop.Tag = int.Parse(tmrAutoStop.Tag.ToString()) + 1;

and check if it reached your desired number:

并检查它是否达到您想要的数量:

if (int.Parse(tmrAutoStop.Tag.ToString()) >= 10)
{
  //do timer cleanup
}

Use this same technique to alternate the timer associated event:

使用相同的技术来交替与计时器相关的事件:

if (int.Parse(tmrAutoStop.Tag.ToString()) % 2 == 0)
{
  //do something...
}
else
{
  //do something else...
}

To check elapsed time (in seconds):

要检查经过的时间(以秒为单位):

int m = int.Parse(tmrAutoStop.Tag.ToString()) * (1000 / tmrAutoStop.Interval);