c#实现计时器

时间:2015-05-21 06:40:28

标签: c# timer

我正在努力实现timer比我应该更多,所以我决定在这里发一个问题。

这是我的班级:

public static class CurrentPoint
    {
        public static Single X { get; set; }
        public static Single Y { get; set; }
        public static Single Z { get; set; }
        public static long   ID { get; set; }

        public static float CalcVar { get; set; }
        public static float CalcStatic { get; set; }


        public static bool StartTimeOut()
        {

            return true;
        }
    }

我应该在其中实现一个方法StartTimeOut()。当其他方法执行时,将从另一个类调用StartTimeOut()

StartTimeOut()我应该有timer来检查CalcVar是否会在接下来的30秒中发生变化。

现在,如果愿意的话,我将从TRUE收到StartTimeOut() timer,如果StartTimeOut() false将返回CalcVar,则应退出。{/ p>

CurrentPoint.ID的此检查将在同一ID下完成。这意味着如果StartTimeOut()更改定时器检查计时器应退出,TRUE将返回{{1}}。

还应检查定时器是否已经运行,如果CalcVar在相同ID下30秒内达到0,则应再次停止计时器 并且StartTimeOut()再次返回TRUE。

我希望我没有太多地解决这个问题。

1 个答案:

答案 0 :(得分:1)

我创建了一个小样本,确实理解无论何时调用此函数,只要它正在运行,它将保留在while循环中。也许你应该从另一个线程内部调用StartTimeOut()函数......

//do not forget
using System.Timers;

private Timer _timer;
private static long _id;
private static bool _returnValue;
private static int _achievedTime;

public static bool StartTimeOut()
{
  //set your known values (you need to check these values over time
  _id = ID;
  _achievedTime = 0;
  _returnValue = true;

  //start your timer
  Start();

  while(_timer.Enabled)
  {
    //an empty while loop that will run as long as the timer is enabled == running
  }
  //as soon as it stops
  return _returnValue;
}

//sets the timer values
private static void Start()
{
  _timer = new Times(100); //describes your interval for every 100ms
  _timer.Elapsed += HandleTimerElapsed;
  _timer.AutoReset = true; //will reset the timer whenever the Elapsed event is called

  //start your timer
  _timer.Enabled = true; //Could also be _timer.Start();
}

//handle your timer event
//Checks all your values
private static void HandleTimerElapsed(object sender, ElapsedEventArgs e)
{
  _achievedTime += _timer.Interval;
  //the ID changed => return true and stop the timer
  if(ID!= _id)
  {
      _returnValue = true;
      _timer.enabled = false; //Could also be _timer.Stop();
  }
  if(CalcVar == 0) //calcVar value reached 0 => return false and stop the timer
  {
    _returnValue = false;
    _timer.Enabled = false;
  }
  if(_achievedTime = 30000) //your 30s passed, stop the timer
    _timer.Enabled = false;          
}

这就是你所说的简单代码不要测试!