线程中时间判断引发的偶发性异常分析

背景:一个倒计时的线程,每次刷新一秒,在倒计时结束之前执行一些监测数据;时间到监测停止;

问题:偶发性倒计时停止在最后一秒,监测一直持续;

问题怀疑:应该是倒计时线程出现了异常:

原代码:

startTime = DateTime.Now;
endTime = startTime + TimeSpan.FromSeconds(timeSeconds);

Task.Run(() => {
  var timeTicks = ().Ticks;
  while (endTime > DateTime.Now)
  {
    if (cancellationToken.IsCancellationRequested)
    {
      log.Info("线程取消");
      currentState = DialogStateEnum.CountEnd;
      return;
    }
    Application.Current.Dispatcher.Invoke((Action)(delegate ()
    {
      CountTime = new DateTime((endTime - DateTime.Now).Ticks);
    }));

    System.Threading.Thread.Sleep(1000);
    timeTicks = (endTime - DateTime.Now).Ticks;
  }
  currentState = DialogStateEnum.CountEnd;
  Messenger.Default.Send<NotificationMessage>(new NotificationMessage("Close"), "DialogMessage");
 }, cancellationToken);

代码分析: 在while (endTime > DateTime.Now) 判断成功后,当执行到 CountTime = new DateTime((endTime - DateTime.Now).Ticks); 变为了负数;导致线程异常,线程退出。

     线程在执行完判断后,可能发生了卡顿,导致问题发生;

修改后代码:采用临时变量做为判断:

Task.Run(() => {
  var timeTicks = (endTime - DateTime.Now).Ticks;
  while (timeTicks > 0)
  {
    if (cancellationToken.IsCancellationRequested)
    {
      log.Info("线程取消");
      currentState = DialogStateEnum.CountEnd;
      return;
    }
    Application.Current.Dispatcher.Invoke((Action)(delegate ()
    {
      CountTime = new DateTime(timeTicks);

    }));

    System.Threading.Thread.Sleep(1000);
    timeTicks = (endTime - DateTime.Now).Ticks;
  }
  currentState = DialogStateEnum.CountEnd;
  Messenger.Default.Send<NotificationMessage>(new NotificationMessage("Close"), "DialogMessage");
}, cancellationToken);

 

posted @ 2025-07-17 10:53  cdxy2005  阅读(24)  评论(0)    收藏  举报