在我的Xamarin应用程序中,我面临着倒计时的问题。
我想从4秒开始重新开始倒数,每次计时器开始的时候。
对于Timespan.FromSeconds(0)
,我得到的是0,3,2,1,对于Timespan.FromSeconds(0)
部分代码,它会快速地向下打印计数,并且在Timespan.FromSeconds(8)
中它也会进入-1,-2。
代码
private Timer _timer;
private int _countSeconds;
public CameraViewModel() {
Device.StartTimer(TimeSpan.FromSeconds(0), () =>
{
_timer = new Timer();
_timer.Interval = 1000;
_timer.Elapsed += OnTimedEvent;
_countSeconds = 4;
_timer.Enabled = true;
return false;
});
Device.StartTimer(TimeSpan.FromSeconds(4), () =>
{
_timer = new Timer();
_timer.Interval = 1000;
_timer.Elapsed += OnTimedEvent;
_countSeconds = 4;
_timer.Enabled = true;
return false;
});
Device.StartTimer(TimeSpan.FromSeconds(8), () =>
{
// above code used here again
return false;
});
}
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
_countSeconds--;
CountDown = _countSeconds;
if (_countSeconds == 0)
{
_timer.Stop();
}
}
#region Bindable Properties
private string _countDown;
public string CountDown
{
get => _countDown;
set => this.RaiseAndSetIfChanged(ref _countDown, value);
}
#endregion
从4.1倒计时并重置
为计数器创建类级变量或属性
int Counter = 4;
创建单个计时器-不需要多个计时器
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
timer.AutoReset = true;
timer.Start();
当计时器启动时
void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine(Counter);
Counter--;
if (Counter < 0) Counter = 4;
}