2015-10-27 148 views
1

當Windows服務啓動C#Windows服務沒有執行代碼

,我發現這裏的解決方案,但他們並沒有爲我工作,我有以下的代碼,它不執行。

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Diagnostics; 
using System.ServiceProcess; 
using System.Configuration; 
using System.Threading.Tasks; 

namespace TFS_JIRA_sync 
{ 
    public partial class SyncProcess : ServiceBase 
    { 

     public SyncProcess() 
     { 
      InitializeComponent(); 
     } 

     private System.Timers.Timer timer = new System.Timers.Timer(); 

     protected override void OnStart(string[] args) 
     { 

      this.timer.Interval = ScanPeriod.period * 60000; //turn minutes to miliseconds    
      this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);//OnTimer;    
      this.timer.Enabled = true; 
      this.timer.AutoReset = true; 
      this.timer.Start(); 
     } 

     private void OnTimer(object sender, System.Timers.ElapsedEventArgs e) 
     { 
      Processing proc = new Processing(); 
      proc.doProcess(); 
     } 

     protected override void OnStop() 
     { 
     } 
    } 
} 

在PROGRAMM:

using System; 
using System.Collections.Generic; 
using System.ServiceProcess; 
using System.Threading.Tasks; 

[assembly: log4net.Config.XmlConfigurator(Watch = true)] 


namespace TFS_JIRA_sync 
{ 
    static class Program 
    { 
     /// <summary> 
     /// Главная точка входа для приложения. 
     /// </summary> 
     static void Main() 
     { 
      ServiceBase[] ServicesToRun; 
      ServicesToRun = new ServiceBase[] 
      { 
       new SyncProcess() 
      }; 
      ServiceBase.Run(ServicesToRun); 

      //Processing proc = new Processing(); 
      //proc.doProcess(); 

     } 
    } 
} 

當我開始評論部分 「ServiceBase [] ...」 並取消 「處理......」 在PROGRAMM類正常工作。

但是,當我的代碼運行作爲Windows服務 - 什麼也沒有發生

+0

看起來正確(除了設置['Enabled'](https://msdn.microsoft.com/en-us/library/system.timers.timer.enabled(v = vs.110).aspx) **和**調用['開始'](https://msdn.microsoft.com/en-us/library/system.timers.timer.start(v = vs.110).aspx))。你如何確定它不是*正常工作? –

+0

處理類我有記錄器,記錄執行的步驟。當我開始將我的Programm作爲Win服務時,在日誌中什麼也沒有發生 – Ilya

回答

0

當我看到你的服務是不會運行的所有時間 this.timer.Interval = ScanPeriod.period * 60000;。對於您的場景 ,而不是使用帶定時器的Windows服務(並花費時間解決問題),我建議使用計劃任務(如answer所示)。 它引用了Jon Gallow的​​,這給出了使用計劃任務更好的原因很多。

如果您正在編寫運行計時器的Windows服務,則應該重新評估您的解決方案。

0

看跌到Console.ReadLine()在你的代碼:

static void Main() 
    { 
     ServiceBase[] ServicesToRun; 
     ServicesToRun = new ServiceBase[] 
     { 
      new SyncProcess() 
     }; 
     ServiceBase.Run(ServicesToRun);  
     Console.ReadLine(); 
    } 
+0

如果他們試圖讓他們的代碼作爲服務運行,那肯定無濟於事。他們展示的Main Main的未註釋位是服務應用程序的* standard *'Main',由VS中的「Windows Service」模板創建。 –