2014-09-09 2 views
1

나를 위해 최소한 이것은 System.Timers.Timer을 사용하는 완벽한 예입니다. 유일한 문제는 내가 Console.ReadLine()을 제거하면 작동하지 않는다는 것입니다. 제 경우에는 5 초가 지난 후 메시지를 표시하고 콘솔을 닫으려고합니다. 그게 전부 야.MSDN Timer.Elapsed 예제는 사용자 개입없이 어떻게 작동합니까?

그럼 사용자 상호 작용없이 간단한 메시지 Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime)을 표시하고 싶습니다. 어떻게 할 수 있습니까? 즉, F5를 누르면 공백의 콘솔 창이 표시되고 5 초 후에 메시지가 표시되고 콘솔이 사라집니다.

다음은 MSDN에서 코드입니다 : 여러 가지 방법이 있습니다

using System; 
using System.Timers; 

public class Example 
{ 
    private static Timer aTimer; 

    public static void Main() 
    { 
     // Create a timer with a two second interval. 
     aTimer = new System.Timers.Timer(5000); 
     // Hook up the Elapsed event for the timer. 
     aTimer.Elapsed += OnTimedEvent; 
     aTimer.Enabled = true; 

     Console.WriteLine("Press the Enter key to exit the program... "); 
     Console.ReadLine(); 
     Console.WriteLine("Terminating the application..."); 
    } 

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

Thread.Sleep이 (가) 불충분합니까? –

+0

@MikeMiller OP [이미 시도] (http://stackoverflow.com/questions/25747006/replace-thread-sleep-with-system-threading-timer)와 무언가가 작동하지 않습니다. 적어도이 문제는 간단합니다. –

답변

3
using System; 
using System.Threading; 
using System.Timers; 
using Timer = System.Timers.Timer; 

private static Timer aTimer; 
private static ManualResetEventSlim ev = new ManualResetEventSlim(false); 

public static void Main() 
{ 
    // Create a timer with a two second interval. 
    aTimer = new System.Timers.Timer(5000); 
    // Hook up the Elapsed event for the timer. 
    aTimer.Elapsed += OnTimedEvent; 
    aTimer.Enabled = true; 
    ev.Wait(); 
} 

private static void OnTimedEvent(Object source, ElapsedEventArgs e) 
{ 
    Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime); 
    ev.Set(); 
} 
+0

잘 근무했습니다. 감사합니다. – vmgmail

2

. 당신이 메인 스레드가 종료 될 때

using System; 
using System.Timers; 

public class Example 
{ 
    private static Timer aTimer; 
    private static bool delayComplete = false; 

    public static void Main() 
    { 
     // Create a timer with a two second interval. 
     aTimer = new System.Timers.Timer(5000); 
     // Hook up the Elapsed event for the timer. 
     aTimer.Elapsed += OnTimedEvent; 
     aTimer.Enabled = true; 

     while (!delayComplete) 
     { 
     System.Threading.Thread.Sleep(100); 
     } 
    } 

    private static void OnTimedEvent(Object source, ElapsedEventArgs e) 
    { 
     Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime); 
     delayComplete = true; 
    } 
} 
2

당신의 응용 프로그램이 종료됩니다

다음은 한 예입니다. 이것이 Main()을 실행하는 스레드입니다. 타이머가 다른 스레드에서 실행됩니다. 따라서 Console.ReadLine()을 사용하지 않으려면 기본적으로 Thread.Sleep (5000)을 사용하십시오. 여기서 5000은 스레드가 잠자기 시간 (밀리 초)입니다. 이렇게하면 타이머가 작동 할 때까지 메인 스레드가 대기하게됩니다.

관련 문제