首页 > 解决方案 > 倒计时在 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

标签: c#xamarin.net-corexamarin.forms

解决方案


从 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;
}

推荐阅读