【问题标题】:Update variable every second during timer execution在计时器执行期间每秒更新变量
【发布时间】:2017-05-06 20:55:19
【问题描述】:

我有一个运行 18 秒的计时器,我想知道在计时器倒计时期间是否可以每 1.5 秒更新一次变量。

只有两个计时器会更容易吗?一个为 18 秒,另一个为 1.5 秒。

还有其他更简单或更好的方法吗?

【问题讨论】:

  • 请向我们展示您的计时器功能。你用的是什么定时器?如果您使用的计时器具有以毫秒为单位获取当前倒计时时间的方法,则可以使用模 1500,例如 if(currentcountdownTimeInMs % 1500 == 0) ...

标签: c#


【解决方案1】:

使用 Microsoft 的响应式框架 (NuGet "System.Reactive")。然后你可以这样做:

long x = 0L;
Observable
    .Interval(TimeSpan.FromSeconds(1.5))
    .Take(12) // 18 seconds
    .Subscribe(n =>
    {
        //update variable
        x = n;
    }, () =>
    {
        //Runs when timer ends.
    });

它避免了您所询问的所有肮脏的计时器。

不过,简而言之,如果您想使用计时器,那么在 1.5 秒的时间间隔内您只需要一个 - 但在 12 次后停止,以给您 18 秒的时间。

【讨论】:

  • 谢谢,这真的很有帮助。
  • 我决定使用设置为 1.5 秒的计时器,因为该程序应该可以在我大学校园内的任何计算机上运行,​​我认为该程序应该可以正常运行,而无需安装其他组件。
  • 如果您需要严格要求 18 秒,您可能会发现 1.5 秒计时器会漂移,并且 12 次重复总是会持续超过 18 秒。时间持续不少于 1.5 秒,因此通常更长。结果是错误将累积 12 倍。同样,如果您的公差松散或重复次数仍然很低,则无关紧要。
  • @DeclanMarks 引用 NuGet 包并不意味着最终用户必须安装其他组件。事实上,如果你展望未来(.Net Core),整个框架由 NuGet 包组成。
  • @rfreytag 使用 Reactive 时是否可以从另一个类启动它。
【解决方案2】:
 public partial class Form1 : Form
{
    Timer timer = new Timer();
    private long Elapsed;

    public Form1()
    {
        InitializeComponent();
        // set interval to 1.5 seconds 1500 (milliseconds)
        timer.Interval = 1500;
        // set tick event withs will be runt every 1.5 seconds  1500 (milliseconds)
        timer.Tick += OnTimerTick;
        // start timer
        timer.Start();
    }

    private void OnTimerTick(object sender, EventArgs e)
    {
        // add 1500 milliseconds to elapsed 1500 = 1.5 seconds
        Elapsed += 1500;
        // check if 18 seconds have elapsed
        // after 12 times it will be true 18000 / 1500 = 12
        if (Elapsed == 18000) 
        {
            // stop the timer if it is
            timer.Stop();
        }
        // update variable
    }
}

【讨论】:

    【解决方案3】:

    我为此使用 async/await - 这有助于我使用没有事件计时器的 PCL

        private async void RunTimerAsync()
        {
               await Timer();
        }
    
        private async Task Timer()
        {
             while (IsTimerStarted)
             {
                   //Your piece of code for each timespan
                   //ElapsedTime += TimeSpan.FromSeconds(1.5);
                   await Task.Delay(TimeSpan.FromSeconds(1.5));
             }
       }
    

    【讨论】:

    • Task.Delay 在内部使用 Timer。此外,您还需要扩展您的答案以包括 18 秒刻度
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 2021-09-24
    相关资源
    最近更新 更多