fix: 优化休息时间计算逻辑,使用计数器避免时间跳变

This commit is contained in:
2026-01-17 13:26:14 +08:00
parent ff8c7f032d
commit e26c015e09

View File

@@ -16,6 +16,7 @@ namespace TimerApp
private DateTime _lastWorkStartTime;
private TimeSpan _accumulatedWorkTime;
private DateTime _restStartTime;
private int _restElapsedSeconds; // 休息已过秒数(用于避免时间计算导致的跳变)
// 配置 (默认值)
public TimeSpan WorkDuration { get; set; } = TimeSpan.FromMinutes(20);
@@ -73,10 +74,12 @@ namespace TimerApp
if (CurrentState == MonitorState.Resting)
{
// 休息模式逻辑
TimeSpan timeInRest = DateTime.Now - _restStartTime;
TimeSpan remainingRest = RestDuration - timeInRest;
// 使用计数器而不是时间差,避免秒数跳变
_restElapsedSeconds++;
int totalRestSeconds = (int)RestDuration.TotalSeconds;
int remainingSeconds = totalRestSeconds - _restElapsedSeconds;
if (remainingRest <= TimeSpan.Zero)
if (remainingSeconds <= 0)
{
// 休息结束
RestEnded?.Invoke(this, EventArgs.Empty);
@@ -84,6 +87,7 @@ namespace TimerApp
}
else
{
TimeSpan remainingRest = TimeSpan.FromSeconds(remainingSeconds);
RestProgressChanged?.Invoke(this, remainingRest);
}
}
@@ -130,6 +134,7 @@ namespace TimerApp
{
// 触发休息
_restStartTime = DateTime.Now;
_restElapsedSeconds = 0; // 重置休息计数器
ChangeState(MonitorState.Resting);
RestStarted?.Invoke(this, EventArgs.Empty);
}
@@ -145,6 +150,7 @@ namespace TimerApp
public void ForceRest()
{
_restStartTime = DateTime.Now;
_restElapsedSeconds = 0; // 重置休息计数器
ChangeState(MonitorState.Resting);
RestStarted?.Invoke(this, EventArgs.Empty);
}
@@ -158,8 +164,11 @@ namespace TimerApp
}
else if (CurrentState == MonitorState.Resting)
{
TimeSpan timeInRest = DateTime.Now - _restStartTime;
TimeSpan remaining = RestDuration - timeInRest;
// 使用计数器计算剩余时间,保持一致性
int totalRestSeconds = (int)RestDuration.TotalSeconds;
int remainingSeconds = totalRestSeconds - _restElapsedSeconds;
if (remainingSeconds < 0) remainingSeconds = 0;
TimeSpan remaining = TimeSpan.FromSeconds(remainingSeconds);
RestProgressChanged?.Invoke(this, remaining);
}
}