2014-01-22 211 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