2013-05-02 14 views
1

我有一個C#程序不斷檢查新的在線數據庫。我有這樣的代碼有它檢查每10秒更好的方式來定期在C中定期運行函數#

static void Main(string[] args) 
    { 
     boolean run = true; 
     while (run) 
     { 
      DBConnect Db = new DBConnect(); 

      // do amazing awesome mind blowing cool stuff 

      Db.closeConnection(); 

      // wait for 10 seconds 
      int wait = 10 * 1000; 
      System.Threading.Thread.Sleep(wait); 
     } 
    } 

我有錯誤報告的帖子到數據庫,如果出現重大錯誤的程序關閉。在我的函數內部的特定錯誤之外,這種方法是否安全有效?

+1

您對「安全」和「高效」的定義是什麼? – 2013-05-02 22:42:05

+0

是什麼讓你覺得有什麼不同? – 2013-05-02 22:42:41

+0

高效=不使用不必要的資源,安全=持續運行的穩定程序@PeteBaughman – Dan 2013-05-02 22:43:54

回答

14

你應該將你的程序改寫爲一個windows服務,這樣你就不需要依賴一個用戶來記錄你的程序運行。

如果你確實走了服務路線,我會換掉定時器的無限循環。

public partial class Service1 : ServiceBase 
{ 
    public Service1() 
    { 
     InitializeComponent(); 
     int wait = 10 * 1000; 
     timer = new Timer(wait); 
     timer.Elapsed += timer_Elapsed; 

     // We don't want the timer to start ticking again till we tell it to. 
     timer.AutoReset = false; 
    } 

    private System.Timers.Timer timer; 

    protected override void OnStart(string[] args) 
    { 
     timer.Start(); 
    } 

    void timer_Elapsed(object sender, ElapsedEventArgs e) 
    { 
     try 
     { 
      DBConnect Db = new DBConnect()) 
      try 
      { 
       // do amazing awesome mind blowing cool stuff 
      } 
      finally 
      { 
       Db.closeConnection(); //We put this in a finally block so it will still happen, even if an exception is thrown. 
      } 
      timer.Start(); 
     } 
     catch(SomeNonCriticalException ex) 
     { 
      MyExecptionLogger.Log(ex, Level.Waring); //Log the exception so you know what went wrong 
      timer.Start(); //Start the timer for the next loop 
     } 
     catch(Exception ex) 
     { 
      MyExecptionLogger.Log(ex, Level.Critical); //Log the exception so you know what went wrong 
      this.Stop(); //Stop the service 
     } 
    } 

    protected override void OnStop() 
    { 
     timer.Stop(); 
    } 
} 
+0

非常酷,所以一個Windows服務本質上運行在後臺,無論哪個用戶登錄?像svchost? – Dan 2013-05-02 22:47:05

+2

是的,就是定義一個服務 – 2013-05-02 22:47:37

+0

非常簡單有效,謝謝您花時間賜教! – Dan 2013-05-02 22:54:46

4

將其作爲控制檯程序編寫而不用等待,並設置一個定期運行的計劃任務。你想每10秒運行一次?每一分鐘?只需更改計劃的任務。

您可以使用任務計劃程序GUI或schtasks命令行工具。

請參閱Programs are not cats

+0

哦,男人,這是一個很好的選擇 - 我不知道選擇哪個答案! – Dan 2013-05-02 22:52:16

+1

貓是什麼東西? :) 也是一個很好的選擇,投票 – 2013-05-02 23:19:55