C# timer stop after some number of ticks automatically

前端 未结 5 1852
梦谈多话
梦谈多话 2021-01-18 05:53

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

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

5条回答
  •  醉话见心
    2021-01-18 06:13

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

    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);
    

提交回复
热议问题