-2

此代码用于评估计时器提供的信息。我希望它在计时有效时激活,并且我希望计时器在某些条件发生时重置。我希望代码不断检查这些参数。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
              }
          }
     }
}
4

2 回答 2

1

One obvious problem that I see--the stopwatch is stopped for basically the whole loop. It's not going to do anything resembling keeping proper time.

于 2013-04-14T16:42:57.483 回答
0

我在这里看到的一个重要标志是您正在通过迭代 for 循环来轮询秒表。这会使用不必要的 CPU 资源。最好切换到事件驱动系统,使用System.Timers.Timer对象并按照逻辑要求启用它们。下面是在上面的示例中使用 Timers 来实现您的逻辑。设置一个定时器,每 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");
    }
}
于 2013-04-14T17:15:12.070 回答