我正在使用MVVM方法在不同的应用程序状态下如何管理计时器?

我有一个运行良好的计时器,我遇到的问题是当应用程序处于睡眠模式或最小化时或在我按下“后退”按钮时,要保持计时器运行,计时器只有在我停下来时才停止我已经完成的按钮。

/// <summary>
/// Starts the timer
/// </summary>
private void StartCommandaction()
{
    CancellationTokenSource cts = _cancellationTokenSource; // safe copy
    Device.StartTimer(TimeSpan.FromSeconds(1),() =>
    {
        if (cts.IsCancellationRequested)
        {
            return false;
        }
        else
        {
            Device.BeginInvokeonMainThread(() =>
            {
                var totalTimeInt = string.IsnullOrEmpty(TxtTotalTime.Value) ? 0  : int.Parse(TxtTotalTime.Value);
                var totalSec = (int)TotalSeconds.TotalSeconds;
                TimeSpan _TimeSpan = new TimeSpan(totalTimeInt,totalSec); //TimeSpan.FromSeconds(TotalSeconds.TotalSeconds);
                LblTime = string.Format("{0:00}:{1:00}:{2:00}",_TimeSpan.Hours,_TimeSpan.Minutes,_TimeSpan.Seconds);
                IsVisibleTimerLabel = true;
                Count();
            });

            return true;
        }
    });

    IsVisibleButtonStart = false;
    IsVisibleButton = true;
}
leemr66 回答:我正在使用MVVM方法在不同的应用程序状态下如何管理计时器?

在不了解其余源代码的情况下,有以下几点使我感到震惊:您期望将计时器事件每秒精确地引发一次,并采用文本表示来计算总时间。这可能适用于当前的计时器实现,但是不能保证。更糟糕的是,您的实现对不同的计时器实现而言不够健壮。

在每次迭代中总结时间时,总时间的误差会越来越大。根据您的用例,这可能无关紧要,但是幸运的是,解决此问题的方法也就是您要解决的问题的方法。

我的建议是:不要总结时间,但要引入固定参考。在第一顺序中,它可能是DateTime(如果精度对您而言很重要,则您的解决方案看起来会有所不同,因此DateTime.Now的精度就可以),但是Stopwatch可以还是把戏。

第一次启动计时器时,请将当前DateTime.Now值存储在成员变量中,然后使用该值来计算经过的时间

CancellationTokenSource cts = _cancellationTokenSource; // safe copy
this._startedAt = DateTime.Now;

Device.StartTimer(TimeSpan.FromSeconds(1),() =>
{
    if (cts.IsCancellationRequested)
    {
        return false;
    }
    else
    {
        Device.BeginInvokeOnMainThread(() =>
        {
            TimeSpan _TimeSpan = DateTime.Now - _startedAt;
            LblTime = _TimeSpan.ToString("hh:mm:ss);
            IsVisibleTimerLabel = true;
            Count();
        });

        return true;
    }
});

请注意::要格式化TimeSpan,可以使用带有格式化字符串的ToString方法。有关如何格式化{{ 1}}根据您的需要的值)

这样,返回页面时,您只需重启计时器即可(无需设置TimeSpan )。由于您已经设置了_startedAt,因此计时器将继续运行并显示正确的时间。

本文链接:https://www.f2er.com/3167472.html

大家都在问