2017-09-11 85 views
1

在我的Window服務應用程序中,定時器功能從不被調用。我將服務部署在我的機器上,然後將服務連接到Visual Studio,並使用不同功能的斷點。在OnStart()之後,我的功能都沒有被調用。C#窗口服務不調用定時器功能

這是我OnStart()功能

protected override void OnStart(string[] args) 
{ 
    this.timer = new System.Timers.Timer(50000); 
    this.timer.AutoReset = true; 
    this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick); 
    this.timer.Start(); 
} 

更新2017年9月12日:添加的事件登錄嘗試,趕上 然後,這個函數調用timer1_tick()

private void timer1_Tick(object sender, EventArgs e) 
{ 
    try 
    { 
     EventLog.WriteEntry("Running.."+ e.ToString()); 
    } 
    catch (Exception ex) 
    { 
     EventLog.WriteEntry("Caught Exception "+ex.ToString(), EventLogEntryType.Error); 
    } 
} 

timer1_tick不會被調用。有什麼建議麼?

更新12/09/2017:我檢查了事件日誌。在Windows日誌>應用程序下,我可以看到消息,服務已成功啓動。但是,添加在try-catch塊中的事件日誌不會顯示。不知道我是否缺少一些東西。

我將該服務附加到Visual Studio進行調試。在下圖中,調用OnStart()方法。我剛添加的Thread.Sleep(30000)讓我得到一些緩衝時間的過程附加到調試器,以避免跳過OnStart()功能

enter image description here

定時器啓動後,我有)對TimerTick斷點(函數期待它被擊中,但它從來不

enter image description here

+0

你確實等了很久?愚蠢的問題,但你永遠不會知道:) –

+0

嘗試用較低的時間間隔進行初始化,並將try \ catch放入timer1_Tick中,如果發生異常,則記錄該異常。 –

+0

@MartinoBordin我把間隔減少到5秒,並添加了一個try-catch塊,但我沒有收到電子郵件。 –

回答

2

timer1_Tick很可能被稱爲一切都在你的OnStart似乎是適當的。也許你沒有收到電子郵件的原因是因爲_SendEmail正在拋出異常。

寫入EventLog可能會提供更多信息?

private void timer1_Tick(object sender, EventArgs e) 
{ 
    try 
    { 
     SendMail._SendMail("Processing A started at" + DateTime.Now.ToString()); 
     Logging.log.LogInput("start refund process"); 
    } 
    catch (Exception ex) 
    { 
     EventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error); 
    } 
} 

正如我還要寫EventLogOnStartOnStop的最佳實踐。

protected override void OnStart(string[] args) 
{ 
    // Log a service start message to the Application log. 
    EventLog.WriteEntry("My Service in OnStart."); 

    timer = new System.Timers.Timer(50000); 
    timer.AutoReset = true; 
    timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick); 
    timer.Start(); 
} 

protected override void OnStop() 
{ 
    // Log a service stop message to the Application log. 
    EventLog.WriteEntry("My Service in OnStop."); 
} 
+0

我按照你的建議添加了事件日誌。我甚至將它們添加到try塊中,但事件查看器不顯示任何消息。它顯示服務已成功啓動,但沒有任何提供。 –

+0

@AnanthKumble您的問題不在您提供的代碼中。我創建了一個沒有任何內容的簡單服務,但計時器和預期的工作。你的服務是否繼續運行,也許它正在崩潰? –

+0

服務繼續保持運行。即使我創建了一個不同的Window Service項目,並按預期調用了定時器函數。我正在嘗試解決現有窗口服務項目中的問題 –