2012-05-15 28 views
0

我正在嘗試使「簡單」計時器從15分鐘到0秒。我在15分鐘內用了900秒。當我運行該程序時,它運行良好,但繼續進行否定。我仍然是C#的新手。我希望代碼在0處停下來並運行警報以吸引別人的注意力。以下是我迄今不可阻擋的計時器

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

namespace GBS_GI_Timer 
{ 
    public class Program 
    { 
     public static int t = 2; 

     public static void Main() 
     { 
      System.Timers.Timer aTimer = new System.Timers.Timer(); 

      // Hook up the Elapsed event for the timer. 
      aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 

      aTimer.Interval = 1000; 
      aTimer.Enabled = true; 

      //Console.WriteLine("Press the Enter key to exit the program."); 
      Console.ReadLine(); 


      //GC.KeepAlive(aTimer); 
      if (t == 0) 
      aTimer.Stop(); 
     } 
     public static void OnTimedEvent(object source, ElapsedEventArgs e) 
     { 
      //TimeSpan timeRemaining = TimeSpan.FromSeconds(t); 

      Console.WriteLine("Time remianing..{0}", t); 
      t--; 

      if (t == 0) 
      { 
       Console.WriteLine("\a"); 
       Console.WriteLine("Time to check their vitals, again!"); 
       Console.WriteLine("Press any key to exit..."); 
      } 
      // Console.ReadKey(); 
      Console.ReadLine(); 
     } 
    } 
} 
+0

我很快把它放在一起添加到一個演示,以顯示它將執行並且它將發送一個警報。可能爲什麼我的邏輯至少可以說是殘暴的。 –

回答

1

您將不得不重構您的代碼以使其工作,System.Timers.Timer使用ThreadPool來運行回調例程。

class Program 
{ 
    public static int t = 2; 
    static System.Timers.Timer aTimer = new System.Timers.Timer(); 

    public static void Main() 
    { 

     // Hook up the Elapsed event for the timer. 
     aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 

     aTimer.Interval = 1000; 
     aTimer.Enabled = true; 

     Console.ReadLine(); 
    } 
    public static void OnTimedEvent(object source, ElapsedEventArgs e) 
    { 
     Console.WriteLine("Time remianing..{0}", t); 
     t--; 

     if (t == 0) 
     { 
      Console.WriteLine("\a"); 
      Console.WriteLine("Time to check their vitals, again!"); 
      Console.WriteLine("Press any key to exit..."); 
      aTimer.Stop(); 
      Console.ReadLine(); 
     } 
    } 
} 
+0

這是做到了。我不確定是否可以將計時器聲明爲靜態。我知道我必須在OnTimedEvent方法中以某種方式阻止它。感謝您的幫助。 –

3

你有它的編碼,這樣當你按下回車鍵(或輸入一些東西並回車),它會檢查噸,可停止計時器。你正在檢查是否t == 0,然後停止計時器。如果在您輸入前t小於零,會發生什麼情況?

+0

我曾嘗試過很多這樣的組合,我非常喜歡線程的新手,並且在3年前我只在VB中與定時器混淆。感謝您的幫助 –

0

現在你的程序還有一些其他的邏輯問題,我不確定即使運行它也會做你想要的。

我會重構你的OnTimedEvent只是做

Console.WriteLine(string.Format("{0} time to check their vitals!")); 

和使用while循環來檢查主程序T的狀態。

你也可以進入處理程序時,這樣沒有其他事件觸發,直到他們承認的第一個事件改變Timer.Interval,但你不能保證這個程序15分鐘運行...

+0

當倒計數達到0時,這給了我一個未處理的異常,並且沒有在一秒鐘內打勾並在大約3秒鐘內完成所有數字。 –