System.Timers.Timer 如何获取到 Elapse 的剩余时间 [英] System.Timers.Timer How to get the time remaining until Elapse
本文介绍了System.Timers.Timer 如何获取到 Elapse 的剩余时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 C#,我如何从 System.Timers.Timer
对象中获取剩余时间(在 elapse 事件发生之前)?
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 => _period;
public DateTime Next => _next;
public TimeSpan DueTime => _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 如何获取到 Elapse 的剩余时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文