此代码用于计算计时器给出的信息。我希望它激活时,定时是有效的,我希望计时器重置时,某些标准发生。我想让代码不断检查这些参数。X, a, b不断变化
Stopwatch sw = new Stopwatch(); //sets sw as the stopwatch variable
sw.Start(); //starts stopwatch
for (int i = 0; ; i++) //counter
{
if (i % 1000000 == 0) //sets counter limit
{
sw.Stop(); //stops stopwatch
if (sw.ElapsedMilliseconds >= 3000) //when the elapsed time is > 3 secs
{
comPort.WriteLine("1"); //sends a 1 to an arduino
break; //breaks for loop
}
else if (sw.ElapsedMilliseconds < 3000) //when the elapsed time is < 3 secs
{
if ((Math.Abs(x-a) < 150) && (Math.Abs(x-b) < 150)) //criteria to start
{
sw.Start(); //continues stopwatch
}
else if ((Math.Abs(x-a) > 150) && (Math.Abs(x-b) > 150)) //criteria reset
{
sw.Reset(); //resets stopwatch
break; //breaks for loop
}
}
}
}
我看到一个明显的问题——秒表基本上在整个循环中都停止了。它不会做任何类似计时的事情
我在这里看到的一个重要标志是,您通过迭代for循环来轮询秒表。这会占用不必要的CPU资源。最好是切换到事件驱动系统,使用System.Timers.Timer
对象,并按照逻辑指示启用它们。下面是上面例子中使用计时器实现的逻辑。设置一个定时器,每500毫秒检查一次x的值,并相应开启3秒定时器。
using System;
using System.Timers;
public class HelloWorld
{
static int a = 0, x = 0, b = 100;
static Timer timerOut, timerCheck;
static public void Main()
{
timerOut = new Timer(3000);
timerOut.Elapsed += new ElapsedEventHandler(OnOutElapsed);
timerCheck = new Timer(500);
timerCheck.Elapsed += new ElapsedEventHandler(OnCheckElapsed);
timerCheck.Start();
for(;;) {
Console.WriteLine("Input x or (Q)uit");
string s = Console.ReadLine();
if(s.ToLower() == "q") break;
x = Convert.ToInt32(s);
}
}
private static void OnCheckElapsed(object sender, ElapsedEventArgs e)
{
if((Math.Abs(x-a) < 150) && (Math.Abs(x-b) < 150)) {
if(!timerOut.Enabled) {
Console.WriteLine("starting timer (x={0})",x);
timerOut.Start();
}
}
else if((Math.Abs(x-a) > 150) && (Math.Abs(x-b) > 150)) {
if(timerOut.Enabled) {
Console.WriteLine("stopping timer (x={0})",x);
timerOut.Stop();
}
}
}
private static void OnOutElapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("write to com port");
}
}