2015-10-27 79 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”模板创建。 –