2012-08-30 2 views
12

서비스가 시작되거나 중지되면이 코드에서 powershell 스크립트를 실행합니다.ServiceController 상태가 실제 서비스 상태를 정확하게 반영하지 않습니다.

Timer timer1 = new Timer(); 

ServiceController sc = new ServiceController("MyService"); 

protected override void OnStart(string[] args) 
    { 
     timer1.Elapsed += new ElapsedEventHandler(OnElapsedTime); 
     timer1.Interval = 10000; 
     timer1.Enabled = true; 
    } 

    private void OnElapsedTime(object source, ElapsedEventArgs e) 
    { 
     if ((sc.Status == ServiceControllerStatus.StartPending) || (sc.Status == ServiceControllerStatus.Stopped)) 
     { 
      StartPs(); 
     } 
    } 

    private void StartPs() 
    { 
     PSCommand cmd = new PSCommand(); 
     cmd.AddScript(@"C:\windows\security\dard\StSvc.ps1"); 
     PowerShell posh = PowerShell.Create(); 
     posh.Commands = cmd; 
     posh.Invoke(); 
    } 
내가 cmd를 프롬프트 그러나에서 내 서비스를 죽일 때 잘 작동하고

심지어 내 서비스가 실행되면, PowerShell 스크립트 왜 (이 컴퓨터에서 파일을 추가합니다) 어떤 생각을 자신을 계속 실행하면?

+0

powershell이이 질문과 직각을 이룬다는 것이 맞겠습니까? 그리고 실제 질문은 : 왜 내 StartPending/Stopped 검사가 제대로 작동하지 않습니까? –

+0

정확히 무슨 일이 일어나고 있는지 확인하기 위해 중단 점을 두어 본 적이 있습니까? –

답변

28

ServiceController.Status 속성 은 항상 라이브가 아닙니다.; 그것은 처음 요청이 지연되면 평가되지만 (요청하지 않는 한) 그 시간; 이후의 Status에 대한 쿼리는이 실제 서비스를 정상적으로 점검하지 않습니다. 이 강제로 추가

sc.Refresh(); 

당신의 .Status 확인하기 전에 :

private void OnElapsedTime(object source, ElapsedEventArgs e) 
{ 
    sc.Refresh(); 
    if (sc.Status == ServiceControllerStatus.StartPending || 
     sc.Status == ServiceControllerStatus.Stopped) 
    { 
     StartPs(); 
    } 
} 

을 그 sc.Refresh()없이, (예를 들어) Stopped 있다면 처음에, 그것은 항상Stopped을 말할 것이다.

+2

고마워요. 그건 꽤 블 랭킹 불쾌한 ... – Will

+0

어! 진심으로, 마이크로 소프트? 왜'Status' 호출 자체에 새로 고침을하지 않는가? (아마 나 자신을 끝내 겠지?) ?? 또는 적어도 "Status.Refresh"메서드를 사용하여 명확하게 알 수 있습니다. – SteveCinq

+1

와우 맨 !! @ 마르크 당신은 내 하루를 보냈습니다. 최신 상태를 확인하기 위해 sc.Refresh()를 호출해야한다는 것을 이해하는 것은 명백하지 않습니다. –

관련 문제