定时器执行期间每秒更新一次变量

问题描述:

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

只需要2个定时器一个18秒另一个定时器1.5秒更容易。

是否有任何其他方法可以更容易或更好。

+0

请告诉我们您的定时器功能。你正在使用什么计时器?如果您使用的计时器有一种方法,您可以以毫秒为单位获得当前的倒计时时间,则可以使用模1500,如if(currentcountdownTimeInMs%1500 == 0)... –

使用微软的Reactive Framework(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秒。

+2

谢谢,这真的有所帮助。 –

+0

我希望使用计时器设置为1.5秒,因为这个程序应该可以在我大学校园里的任何一台计算机上工作,我认为该程序应该工作而无需安装其他组件。 –

+0

如果你的第18条要求很紧,你可能会发现1.5秒计时器漂移,12次重复始终持续18秒多一点。时间不少于1.5秒,所以通常更长。结果是错误将累积12倍以上。再说一遍,如果你的容忍度很低或者重复次数依然很少,那就不重要了。 – rfreytag

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

我使用异步/等待为 - 帮我带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)); 
     } 
    } 
+1

Task.Delay在内部使用Timer。此外,您还需要延长您的答案以包括18秒钟的时间 –