2012-11-21 188 views
3

我寫了一個windows服務,它反過來調用一個web服務。 當我從測試應用程序運行Windows服務時,它完美地工作。但是,當我安裝服務然後啓動它時,它幾乎立即停止。我在日誌中看到的唯一兩個條目是構造函數已啓動線程。不知道什麼是錯的。Windows服務立即啓動並退出

public partial class WindowsService : ServiceBase 
{ 
    public LogManager.LogFile _log; 
    public Thread m_thread; 
    protected TimeSpan m_delay; 

    CommonFunctions _cf = new CommonFunctions(); 
    DBFunctions _db = new DBFunctions(); 

    public WindowsService() 
    { 
     InitializeComponent(); 
     _log = new LogManager.LogFile(@"c:\test\servicelog.txt", true, true); 
     _log.WriteToLog("Constructor", LogLevel.Level0); 
    } 


    protected override void OnStart(string[] args) 
    { 

     m_delay = new TimeSpan(0,0,300); 
     base.OnStart(args); 

     try 
     { 
      m_thread = new System.Threading.Thread(Execute); 
      m_thread.Start(); 
      _log.WriteToLog("Thread Started", LogLevel.Level0); 
     } 
     catch (Exception ex) 
     { _log.WriteToLog(ex.Message, LogLevel.Level0); } 

    } 

    public void Execute() 
    { 
     _log.WriteToLog("Begin Execute...", LogLevel.Level0); 

     try 
     { 

      ProcessNewLMSUsers(); 

     } 
     catch (Exception ex) 
     { 
      _log.WriteToLog(ex.Message.ToString()); 
     } 

    } 

    private void ProcessNewLMSUsers() 
    { 
     try 
     { 
      _log.WriteToLog("Begin: Processing new LMS Users", LogLevel.Level1); 

      // Check for new users in the LMS. 
      string callErrorText = ""; 
      bool userAdded = false; 

      LMSWS.SSO lms = _cf.GetLMSSSOWS(); **// this is a web service** 
      lms.Timeout = 99999; 


      } 

      REST OF THE CODE................. 
    } 
+0

您是否檢查過系統日誌? 查看此問題的接受答案以獲得概述。 http://stackoverflow.com/questions/1067531/are-there-any-log-file-about-windows-services-status – 5arx

回答

0

我看不出你的代碼有什麼問題。但是你可以嘗試在OnStart方法開始時放置一個「Thread.Sleep(20000);」代碼。例如

protected override void OnStart(string[] args) 
{ 
    Thread.Sleep(20000); 

    m_delay = new TimeSpan(0,0,300); //set a break-point here 
    base.OnStart(args); 

    try 
    { 
     m_thread = new System.Threading.Thread(Execute); 
     m_thread.Start(); 
     _log.WriteToLog("Thread Started", LogLevel.Level0); 
    } 
    catch (Exception ex) 
    { _log.WriteToLog(ex.Message, LogLevel.Level0); } 

} 

並且一旦您在Windows服務中啓動此服務程序,則必須快速將源代碼附加到服務程序。在Visual Studio中,它的菜單是「Debug」 - >「Attach to Process ...」。那麼你可以在你的源代碼中的任何地方設置斷點來檢查發生了什麼問題。

+1

呼叫替換調用到'System.Threading.Thread.Sleep(20000)'調用'System.Diagnostics.Debugger.Launch()'。這應該會導致在啓動服務時彈出一個對話框,允許您在調用時暫停代碼的情況下打開Visual Studio的調試會話。我被告知這可能不適用於Windows 8,FYI。 –

+0

謝謝!並對延遲迴復表示抱歉。我能夠使用Syste.Diagnostics.Debugger.Launch()調試代碼,發現代碼工作正常,但沒有寫入日誌文件。我將值更改爲logLevel.Level0並使其工作。但現在我有另一個問題。 Windows服務已安裝並正在運行。但是Execute()只執行一次。我如何定期執行它?再次感謝! – stackuser

+0

通常我在線程方法('Execute'here)中放置'while'循環。 – yyou