Timer如何获取到过去为止的剩余时间

Timer如何获取到过去为止的剩余时间

本文介绍了System.Timers.Timer如何获取到过去为止的剩余时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#,如何从System.Timers.Timer对象获取剩余时间(发生经过事件之前)?

Using C#, how may I get the time remaining (before the elapse event will occur) from a System.Timers.Timer object?

换句话说,假设我将计时器间隔设置为6小时,但是3小时后,我想知道还剩下多少时间.我将如何获取计时器对象以显示剩余时间?

In other words, let say I set the timer interval to 6 hours, but 3 hours later, I want to know how much time is remaining. How would I get the timer object to reveal this time remaining?

推荐答案

内置计时器不会提供剩余时间,直到经过时为止.您需要创建自己的类,该类包装计时器并公开此信息.

The built-in timer doesn't provide the time remaining until elapse. You'll need to create your own class which wraps a timer and exposes this info.

类似的事情应该起作用.

Something like this should work.

public class TimerPlus : IDisposable
{
    private readonly TimerCallback _realCallback;
    private readonly Timer _timer;
    private TimeSpan _period;
    private DateTime _next;

    public TimerPlus(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
    {
        _timer = new Timer(Callback, state, dueTime, period);
        _realCallback = callback;
        _period = period;
        _next = DateTime.Now.Add(dueTime);
    }

    private void Callback(object state)
    {
        _next = DateTime.Now.Add(_period);
        _realCallback(state);
    }

    public TimeSpan Period
    {
        get
        {
            return _period;
        }
    }

    public DateTime Next
    {
        get
        {
            return _next;
        }
    }

    public TimeSpan DueTime
    {
        get
        {
            return _next - DateTime.Now;
        }
    }

    public bool Change(TimeSpan dueTime, TimeSpan period)
    {
        _period = period;
        _next = DateTime.Now.Add(dueTime);
        return _timer.Change(dueTime, period);
    }

    public void Dispose()
    {
        _timer.Dispose();
    }
}

这篇关于System.Timers.Timer如何获取到过去为止的剩余时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 17:55