2016-09-08 5 views
1

Timer (System.Timers.Timer)를 사용할 때 특히 문제가 있습니다. 내 코드를 확인한 결과 내 추론에서 잘못된 점을 발견 할 수 없습니다. 나는 이것에 대한 통찰력을 매우 고맙게 생각한다.C#의 타이머가 작동하지 않습니다.

나는 프로그램을 수행 할 작업이이 개 무한 루프 다른 (keepRunning라는 하나와 다른 하나 keepTrying) 내부의 하나. Ctrl-C를 누르면 루프가 유한 해지고 프로그램이 정상적으로 종료됩니다.

루프 내에서 사용자에게 Enter 키를 계속 누릅니다. 왜?

글쎄, 나는 또한 타이머가있다. 이 타이머는 3 초마다 기능을 호출합니다. 이 함수가 10 번 호출되면 keepTrying 루프 이되어야하고 주 프로그램이이 루프를 종료해야합니다. ("시도 중"과 "시도 시작"콘솔에 인쇄하여 명확하게 나타냅니다.)

사용자가 Enter를 누르지 않으면 Enter 키를 누르면 타이머가 재설정되고 타이머에 0 모든 것을 다시 시작하게라고도하고.

글쎄, 그것은이 호출되고 계속 루프가 종료되지 않고, 타이머 경과 이벤트가 10 배 이상을 호출되는 경우에도, 어떻게 든. 작동하지 않습니다.

제 코드를 살펴보세요. 작동하도록 제안 해 주시면 고맙겠습니다. 감사합니다.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Timers; 

namespace TimerExample1 
{ 
    class Program 
    { 
     private static Timer aTimer; 
     private static bool keepRunning = true; 
     private static bool keepTrying = true; 
     private static int attempts = 0; 

     static void Main(string[] args) 
     { 
      //We manage to set the way to finish this program with CTRL+C 
      Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e) 
      { 
       e.Cancel = true; //execution continues after the delegate 
       keepRunning = false; 
       keepTrying = false; 
      }; 

      SetTimer(); 

      while (keepRunning) 
      { 
       Console.WriteLine("Start trying"); 
       keepTrying = true; 

       while (keepTrying) 
       { 
        if (attempts > 10) break; 

        Console.WriteLine("Press the Enter key to prevent the timer from firing off..."); 
        Console.ReadLine(); 
        //it was pressed so 
        aTimer.Stop(); 
        aTimer.Start(); 
        attempts = 0; 

       }//keep trying 


       Console.WriteLine("got out of trying"); 
      }//keepRunning 

      Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now); 
      Console.WriteLine("\nPress the Enter key to exit the application..."); 

      aTimer.Stop(); 
      aTimer.Dispose(); 
      Console.ReadLine(); 

      Console.WriteLine("Terminating the application..."); 

     } 
     private static void SetTimer() 
     { 
      // Create a timer with a two second interval. 
      aTimer = new System.Timers.Timer(3000); 
      // Hook up the Elapsed event for the timer. 
      aTimer.Elapsed += OnTimedEvent; 
      aTimer.AutoReset = true; 
      aTimer.Enabled = true; 
     } 

     private static void OnTimedEvent(Object source, ElapsedEventArgs e) 
     { 
      Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}", 
           e.SignalTime); 

      attempts++; 
      if (attempts > 10) keepTrying = false; 
     } 
    } 
} 
+0

루프 내부에 있기 때문에 타이머가 재설정 될 때마다 keepTrying을 false로 설정 한 다음 바깥 쪽 루프에서 true로 설정 한 다음 다시 반복하여 묻습니다. –

+0

설정하지 않았 으면합니다. ctrl-c를 누를 때를 제외하고는'keepRunning'을'false'로 설정하십시오. 따라서 외부 루프를 종료하지 않습니다. – Maarten

+0

답장을 보내 주셔서 감사합니다. 바깥 쪽 루프는 Ctrl-C를 제외하고는 버려진 것이 아닙니다. – KansaiRobot

답변

3

코드의 문제는 Console.ReadLine();이 (가) 작동을 차단하고 있다는 것입니다. 사용자가 Enter 키를 누를 때까지 그 위치에서 멈 춥니 다. ReadLine에서 차단 되었기 때문에 타이머 증가가 횟수만큼 반복되고 아무런 문제가 없으며 루프에서 해당 값이 확인되지 않습니다. keepTrying = false; 차단하지 않는 Console.KeyAvailable을 사용하도록 변경해야합니다. 열쇠가 있다면 Console.ReadKey이며 Enter 키와 비교하십시오. 키가 사용 가능하다면 읽어야합니다. 그렇지 않으면 입력 버퍼를 비울 때까지 항상 KeyAvailable을 가져옵니다.

+0

고맙습니다. 나는 이것을 한 번 더 입력하면 나머지 코드는 작동하는 것으로 나타났습니다. 다시 한 번 감사드립니다! – KansaiRobot

관련 문제