2014-02-10 2 views
0

Windows 서비스를 시작할 때이 오류 메시지가 계속 발생합니다.Windows 서비스가 시작되고 중지됨

로컬 컴퓨터의 서비스가 시작된 다음 중지되었습니다. 일부 서비스는 다른 서비스 및 프로그램에서 사용 중이 아닌 경우 자동으로 중지됩니다.

내 코드 :

 protected override void OnStart(string[] args) 
    { 
     string eventLogMessage = string.Format(@"Notify Service is starting :{0}", DateTime.Now); 
     EventLogging.LogInformation(eventLogMessage); 

      double interval; 

      try 
      { 
       interval = Convert.ToDouble(ConfigurationManager.AppSettings["intervalInSeconds"]); 
       EventLogging.LogInformation(
        string.Format("Loaded configuration: Interval duration is {0} minutes", (interval/60))); 
      } 
      catch (Exception exception) 
      { 
       interval = 3600; 

       eventLogMessage = string.Format("Loading configuration failed: Interval duration is {0} minutes", (interval/60)); 
       eventLogMessage += string.Format("\nMessage was: {0}", exception.Message); 

       EventLogging.LogWarning(eventLogMessage); 
      } 

      interval = interval * 1000; 

      _timer.Interval = interval; 
      _timer.Elapsed += TimerTick; 
      _timer.Start(); 

      eventLogMessage = string.Format(@"Notify service has started: {0}", DateTime.Now); 
      EventLogging.LogInformation(eventLogMessage); 

      var workerThread = new Thread(NotifyUsers) { IsBackground = true }; 
      workerThread.Start(); 

    } 

    private void NotifyUsers() 
    { 
     var userBL = new UserBL(); 

     List<User> usersToBeMailed = userBL.GetAllUsersWhosePasswordsWillExpire(); 

     string eventLogMessage = string.Format("Number of users to be mailed is {0}", usersToBeMailed.Count); 
     EventLogging.LogInformation(eventLogMessage); 

     foreach (User user in usersToBeMailed) 
     { 
      userBL.MailUser(user); 
     } 
    } 

    private void TimerTick(object sender, ElapsedEventArgs e) 
    { 
     var workerThread = new Thread(NotifyUsers) { IsBackground = true }; 
     workerThread.Start(); 
    } 

    protected override void OnStop() 
    { 
     base.OnStop(); 

     string eventLogMessage = @"Password notify service has stopped: " + DateTime.Now; 

     EventLogging.LogInformation(eventLogMessage); 
    } 


    protected override void OnPause() 
    { 
     base.OnPause(); 
     _timer.Stop(); 
     EventLogging.LogWarning("Paused"); 
    } 

    protected override void OnContinue() 
    { 
     base.OnContinue(); 
     _timer.Start(); 
     EventLogging.LogInformation("Resumed"); 
    } 
} 
+0

'OnStart' \'OnStop' 메소드에는 무엇이 있는지에 대해 상당히 엄격한 규칙이 있습니다. 'workerThread' 코드를 추측하고 있습니다. 테스트로서 그것을 제거하고 여전히 중지되는지보십시오. – cjb110

+0

또한 _timer 및 작업자를 별도의 '초기화'방법으로 이동하십시오. 'OnStart'는 완전한 예외 처리로 단순해야합니다. – cjb110

+0

디버거를 서비스에 연결하여 예외 발생 위치를 찾으십시오. OnStart() 메서드의 첫 번째 줄에 Thread.Sleep (30000)을 추가하면 코드가 실행되기 전에 디버거를 연결할 수 있습니다. Thread.Sleep 호출 다음에 중단 점을 잊지 마십시오. 스레드가 깨어있을 때 수동으로 한 줄씩 디버깅 할 수 있습니다. –

답변

0

당신은 살아 과정을 유지하기 위해, 당신의 일을 스레드가 아닌 인 백그라운드 스레드 중 하나 이상 있어야합니다. OnStart 코드가 실행되는 스레드는 실제로 스레드 중 하나가 아니며, 성공적으로 시작된 것으로 간주하려면 OnStart에서 복귀해야합니다.

이 생성 단지 ManualResetEvent 개체를 대기하여 OnStart 방법에서 새로운 Thread을 실행하는 것처럼 간단 할 수있는 당신의 OnStop 코드에서 당신 Set.

또는이 스레드가 수행해야 할 유용한 작업을 찾아보십시오 (그러나 이벤트 객체를 사용하여 종료해야 할 때도 신호를 보냅니다). 또는 두 가지가 있습니다.이 코드가 서비스에 속하는지 여부를 고려하십시오. 정기적으로 사용자에게 알리기 위해 잠깐 깨어있는 경우 예약 된 작업을 사용하지 않는 이유는 무엇입니까?

관련 문제