2012-11-21 130 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