是否有更好的方法来每秒更新一次执行计时器,而不是使用每150毫秒检查一次的后台工作程序?

Tho*_*mas 6 c# winforms

要显示特定进程运行多长时间的计时器,我使用后台工作程序来更新执行时间标签.当然,这应该每秒进行一次,以便用户看到它一直增加.

在尝试了一下并彻底失败后,我走了一条路,我每150毫秒检查一次,如果下一秒已经存在,那么我更新显示器.

    private void ExecutionTimerBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        Stopwatch executionTime = new Stopwatch();
        double lastUpdateAtSeconds = 0;

        executionTime.Start();

        while (!ExecutionTimerBackgroundWorker.CancellationPending)
        {
            Thread.Sleep(150);  // Sleep for some while to give other threads time to do their stuff

            if (executionTime.Elapsed.TotalSeconds > lastUpdateAtSeconds + 1)   // Update the Execution time display only once per second
            {
                ExecutionTimerBackgroundWorker.ReportProgress(0, executionTime.Elapsed);    // Update the Execution time Display
                lastUpdateAtSeconds  = executionTime.Elapsed.TotalSeconds;
            }
        }

        executionTime.Stop();
    }

    private void ExecutionTimerBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // Update the display to the execution time in Minutes:Seconds format
        ExecutionTimeLabel.Text = ((TimeSpan) e.UserState).ToString(@"mm\:ss");    
    }
Run Code Online (Sandbox Code Playgroud)

现在这对我来说似乎有点低效,因为我每150毫秒运行一次,看起来"嘿,下一秒已经到了".我还尝试了一种不同的方法,在那里我计算到下一秒需要多长时间,但是在那一次我有一些实例,其中显示器中每次跳跃2而不是1秒.

所以我的问题是:有没有更有效的方法来做到这一点?或者那已经是应该怎么做了?

Yas*_*usa 0

您可能想看看System.Threading.TimerSystem.Timers.Timer,但说实话,即使您将间隔设置为 1 秒,两者都不是很精确:/大多数时候,我都会选择990ms 或者我使用一个线程就像你使用你的BackgroundWorker一样(我不认为这些计时器的工作原理有什么不同)。

编辑:有趣的是,我刚刚查看了 .NET Framework,Timers.Timer 内部使用了 Threading.Timer。