在C#中设定一个定时器,在一定时间后停止计时。

6

我想每隔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;
    }
}

请您建议是否有更好的方法来执行相同的任务。欢迎提供示例代码。

1个回答

4

您应该在事件中停止计时器并重新启动,以确保您的执行不会两次进入事件。 例如:

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

如果机器非常慢,时间间隔非常小,则在 Stop 方法被处理之前可能会触发新事件。虽然可能永远不会发生,但唯一的保证是尝试获取锁并在无法获取时退出。 - Weyland Yutani
@新员工:假设我的任务(在else块中执行)需要100毫秒才能完成。在这种情况下,实际经过的时间将是200毫秒+100毫秒,但这里没有考虑到 :( 你对此有何看法?如前所述,我想从0开始每隔200毫秒重复执行,直到10秒钟。 - ravi
@RaviJoshi,不对。你的经过时间将是200毫秒,因为你的任务只需要100毫秒,计时器会等待剩余的100毫秒再次触发。 - user2711965

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接