秒表不会停止

StopWatch doesn't stop

我确定逻辑有问题,但我就是想不通是什么。 我正在尝试使用加速度计(phone 运动)来计算用户走了多长时间,如果 3 秒内没有运动,时间应该停止,如果用户再次开始移动,时间应该重新开始并且它应该加到早点达到的时间但是没有运动后时间不会停止。

 public partial class Walking : ContentPage
{
    
    private double lastX;
    private double lastHandledX;
    private TimeSpan timeForRewards;

    Stopwatch stopWatch = new Stopwatch();
    public Walking()
    {
        InitializeComponent();
        Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
        
    }

    private void Accelerometer_ReadingChanged(object sender, AccelerometerChangedEventArgs e)
    {
       
       lastX = e.Reading.Acceleration.X;
      
        acc.Text = $"X: {e.Reading.Acceleration.X}";
    }

    private bool OnTimerTriggered()
    {
        if (lastX!=lastHandledX)
        {
            stopWatch.Start();
            walks.Text = "Yay I am walking";
        }
        else
        {
            stopWatch.Stop();
            timeForRewards += stopWatch.Elapsed;
            walks.Text = $"Oh, we've stopped walking! time: {timeForRewards}";
            
        }
        lastHandledX = lastX;   
        
        return true;
    }
    void StartWalking_Clicked(object sender, EventArgs e)
    {

        if (Accelerometer.IsMonitoring)
        {
            Accelerometer.Stop();
        }
        else Accelerometer.Start(SensorSpeed.UI);

        Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
        Device.StartTimer(new TimeSpan(0, 0, 2), OnTimerTriggered);


    }
  
}

}

使用Stopwatch.Restart()

Stops time interval measurement, resets the elapsed time to zero, and starts measuring elapsed time.

而不是Stopwatch.Start()

Starts, or resumes, measuring elapsed time for an interval.