首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C#计时器在一定数量的滴答后自动停止

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

Stack Overflow用户
提问于 2013-08-07 10:06:49
回答 5查看 28.9K关注 0票数 8

如何在滴答数之后或在3-4秒之后停止计时器?

因此,我启动一个计时器,我希望在10滴答或2-3秒后自动停止。

谢谢!

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2013-08-07 10:10:40

你可以保留一个柜台

代码语言:javascript
运行
复制
 int counter = 0;

然后,在每一个滴答,你增加它。在你的限制之后,你可以停止计时器。在您的滴答事件中这样做。

代码语言:javascript
运行
复制
 counter++;
 if(counter ==10)  //or whatever your limit is
   yourtimer.Stop();
票数 9
EN

Stack Overflow用户

发布于 2013-08-07 10:18:06

当达到定时器指定的间隔(3秒后)时,将调用timer1_Tick()事件处理程序,您可以在事件处理程序中停止定时器。

代码语言:javascript
运行
复制
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;
}
票数 5
EN

Stack Overflow用户

发布于 2013-08-07 10:12:27

假设您使用的是System.Windows.Forms.Tick。你可以跟踪一个柜台,它的生活时间是这样的。使用计时器的标记属性是一种很好的方法。这使得它对其他定时器可重用,并保持代码的通用性,而不是对每个定时器使用全局定义的int counter

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

代码语言:javascript
运行
复制
    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
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18100524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档