2014-01-22 213 views
0

这是我的主:Windows服务启动失败

static class Program 
{ 
    static void Main() 
    { 
     //Debugger.Launch();   
     ServiceBase[] ServicesToRun; 
     ServicesToRun = new ServiceBase[] 
     { 
      new Service1() 
     }; 

     ServiceBase.Run(ServicesToRun); 
    } 
} 

这是我Service1()代码:

public partial class Service1 : ServiceBase 
{ 
    public Service1() 
    { 
     Thread messageThread = new Thread(new ThreadStart(Messaggi.Check)); 
     messageThread.Start(); 

     bool checkGruppoIndirizzi = true; 

     for (; ;) 
     { 
      SediOperative.Check(); 

      Autisti.Check(); 

      AutistiVeicoli.Check(); 

      StatiVega.Check(); 

      int res = Ordini.Check(); 
      if (res == 0) AssegnazioniVega.Check(); 

      Thread.Sleep(10000); 
     } 
    } 

    protected override void OnStart(string[] args) 
    { 
    } 

    protected override void OnStop() 
    { 
    } 
} 

的第一件事是,我不知道,如果以这种方式推出两个线程是这是一个很好的事情,但真正的问题是程序在Visual Studio中运行良好,但安装后(我使用InstallShield创建了一个安装项目)我尝试从Windows服务面板启动我的服务,并得到:

Error 1053: The service did not respond to the start or control request in a timely fashion 

回答

1

您遇到的问题是您的服务将在susyem调用Start方法并且已成功返回后成功启动。假设你在构造函数中有一个无限循环,那么系统就会自言自语:“甚至不能创建这个让我们独自打电话的开始,我放弃了。

您的代码应该沿着这些线路进行重构:

public partial class Service1 : ServiceBase 
{ 
    public Service1() 
    { 
    } 
    private Thread messageThread; 
    private Thread otherThread; 

    private bool stopNow; 

    protected override void OnStart(string[] args) 
    { 
     this.stopNow = false; 
     this.messageThread = new Thread(new ThreadStart(Messaggi.Check)); 
     this.messageThread.Start(); 

     this.otherThread = new Thread(new ThreadStart(this.StartOtherThread)); 
     this.otherThread.Start(); 

    } 

    private void StartOtherThread() 
    { 
     bool checkGruppoIndirizzi = true; 

     while (this.stopNow == false) 
     { 
      SediOperative.Check(); 

      Autisti.Check(); 

      AutistiVeicoli.Check(); 

      StatiVega.Check(); 

      int res = Ordini.Check(); 
      if (res == 0) AssegnazioniVega.Check(); 

      for (int 1 = 0; i < 10; i++) 
      { 
       if (this.stopNow) 
       { 
        break; 
       } 
       Thread.Sleep(1000); 
      } 
     } 
    } 
    } 
    protected override void OnStop() 
    { 
      this.stopNow = true; 
     this.messageThread.Join(1000); 
     this.otherThread.Join(1000); 
    } 
} 

是的,在线程开始的东西也正是这样做的方式你必须在停止阻止他们的一些方法( )方法(上面的代码是空代码,所以不要相信它)对于'otherThread'我已经检查了一个bool并在bool被设置时退出,thread.Join只是一个整理不是必须的,但是我认为是很好的家务。

干杯 -

+0

谢谢我会试试这个解决方案重刑! – Federico