计时器执行期间每秒更新变量



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

只有2个计时器一个持续18秒,而另一个计时器会更容易。

还有其他方法可能更容易或更好。

使用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秒钟。

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

我正在使用异步/等待这一点 - 这对我没有事件计时器

帮助我
    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));
         }
   }

最新更新