c# - 在 C# 中一段时间​​后停止计时器

标签 c# timer

我想以 200 毫秒的间隔重复执行一些操作,从时间 t=0 到 t=10 秒。

目前我正在跟踪变量中耗时。这让我看起来很不舒服。下面是代码-

using System;
using System.Timers;

class Program
{
    static int interval = 200; // 0.2 seconds or 200 ms
    static int totalTime = 10000; // 10 seconds or 10000 ms
    static int elapsedTime = 0; // Elapsed time in ms

    static Timer timer;

    static void Main(string[] args)
    {
        timer = new Timer(interval);
        timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        timer.Enabled = true;

        Console.ReadKey(); // for checking
    }

    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        if (elapsedTime > totalTime)
            timer.Stop();

        else
        {
            // here I am performing the task, which starts at t=0 sec to t=10 sec
        }
        elapsedTime += interval;
    }
}

如果有更好的方法来执行相同的任务,请提出建议。示例代码总是受到赞赏。

最佳答案

您应该停止事件中的计时器并重新开始,以确保您的执行不会两次进入事件。喜欢:

private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
    timer.Stop();
    if (elapsedTime > totalTime)
    {
        return;
    }
    else
    {
        // here I am performing the task, which starts at t=0 sec to t=10 sec
        timer.Enabled = true; //Or timer.Start();
    }
    elapsedTime += interval;
}

关于c# - 在 C# 中一段时间​​后停止计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23500442/

相关文章:

c# - .NET 标准 + .NET 框架 : could not load file or assembly 'Ninject'

c# - MFC 中的硬件加速

c# - ReturnUrl 在使用 ASP.NET Core 6 MVC 的 POST 上始终为 null

c# - 让代码运行 X 秒,然后停止

jquery - HTML5和jQuery:使用音频播放器作为if语句的计时器吗?

按下按钮时的 Java 计时器

c# - Web Api 模型绑定(bind)和多态继承

c# 数学运算的泛型方法

java - EJB 计时器忽略 TransactionTimeout

ios - 动画 24 张大图像 - 每张 728x936 大小