c# - 倒计时在 Xamarin 中无法正常工作
问题描述
在我的 Xamarin 应用程序中,我遇到了倒计时问题。
每次计时器启动时,我都想从4 seconds重新开始倒计时。
对于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 倒计时并重置
为您的 CCounter 创建一个类级别的变量或属性
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;
}
推荐阅读
- javascript - 调用`event.preventDefault`时我做错了什么?
- python - Heroku 上的 Scrapy 爬虫返回 503 服务不可用
- c - -2^31 作为最小整数,为什么?
- c# - 导出 Excel 报表服务器时,现有连接被远程主机强行关闭
- python - 从 PyTorch 中的网络输出计算梯度会出错
- svg - 为什么渲染一组 svg 与一个 svg 不同?
- python - 如何在 python 3.6 中使用分布式包?
- java - 在 Android 5 中支持 JAVA-8 Jar - React Native
- javascript - 设置超时后InnerText闪烁
- in-app-purchase - 如何在 App Purchase 中获取 Volume App Store