2008-11-14 64 views
3

我遇到了我正在處理的管理應用程序的問題。我構建了一個停止,啓動和查詢40多臺服務器上的各種服務的界面。Service.Controller狀態/輪詢

我正在查看service.controller並已成功停止並啓動各種按鈕事件服務,但現在我試圖找出一種方法將服務狀態返回到文本框並查詢服務狀態每10秒鐘左右一次,我覺得自己正在撞牆。

有沒有人有任何提示或見解?

謝謝!

回答

4

您可以使用Timer對象觸發定期服務檢查。您可以在Elapsed事件上運行您的服務查詢。

private void t_Elapsed(object sender, ElapsedEventArgs e) 
    { 
     // Check service statuses 
    } 

至於在文本框中顯示狀態,你應該能夠使用該服務狀態ToString()方法,並顯示在一個常規的文本框中。請記住,在對定時器事件作出反應時,您可能會或可能不會在GUI線程中,因此您需要調用自己的主線程。

private delegate void TextUpdateHandler(string updatedText); 

    private void UpdateServerStatuses(string statuses) 
    { 
     if (this.InvokeRequired) 
     { 
      TextUpdateHandler update = new TextUpdateHandler(this.UpdateServerStatuses); 
      this.BeginInvoke(update, statuses); 
     } 
     else 
     { 
      // load textbox here 
     } 
    } 
2

也許你不希望輪詢:

Private serviceController As ServiceController = Nothing 
Private serviceControllerStatusRunning = False 

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load 
    Try 
     serviceController = New ServiceController("NameOfTheTheServiceYouWant") 
     If serviceController.Status = ServiceControllerStatus.Stopped Then 
      ' put code for stopped status here 
     Else 
      ' put code for running status here 
     End If 
     BackgroundWorker1.RunWorkerAsync() 
    Catch ex As Exception 
     MessageBox.Show("error:" + ex.Message) 
     serviceController = Nothing 
     Me.Close() 
     Exit Sub 
    End Try 
End Sub 

Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork 
    If serviceControllerStatusRunning Then 
     serviceController.WaitForStatus(ServiceControllerStatus.Stopped) 
     serviceControllerStatusRunning = False 
    Else 
     serviceController.WaitForStatus(ServiceControllerStatus.Running) 
     serviceControllerStatusRunning = True 
    End If 
End Sub 

Private Sub BackgroundWorker1_RunWorkerCompleted(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted 
    if serviceControllerStatusRunning then 
     ' put code for running status here 
    else 
     ' put code for stopped status here 
    end if 
    BackgroundWorker1.RunWorkerAsync() ' start worker thread again 
End Sub 

乾杯 孕育