Display time elapsed

后端 未结 3 582
谎友^
谎友^ 2021-01-24 13:30

I need to display the elapsed time dynamically. My code will pop up a message based on an interval value.

public void button1_Click(object sender, EventArgs e)
{         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-24 13:58

    I wouldn't muck about with timers. I'd use Microsoft's Reactive Framework for this. Just NuGet "Rx-Winforms" to get the bits. Then you can do this:

    Observable
        .Create(o =>
        {
            var now = DateTimeOffset.Now;
            var end = now.AddMinutes(15.0);
            return
                Observable
                    .Interval(TimeSpan.FromSeconds(0.1))
                    .TakeUntil(end)
                    .Select(x => end.Subtract(DateTimeOffset.Now).ToString(@"mm\:ss"))
                    .DistinctUntilChanged()
                    .Subscribe(o);
        })
        .ObserveOn(this)
        .Subscribe(x => label1.Text = x);
    

    This will automatically create a countdown timer that will update the text in label1 with the following values:

    14:59 
    14:58 
    14:57 
    14:56 
    14:55 
    14:54 
    ...
    00:02
    00:01
    00:00
    

    If you want to stop this before the timer runs out the Subscribe method returns an IDisposable that you can just call .Dispose().

提交回复
热议问题