Service.Controller状态/轮询

时间:2008-11-14 17:26:57

标签: c# windows visual-studio winapi

我正在处理我正在处理的管理应用程序的问题。我构建了一个界面,用于停止,启动和查询40个左右的服务器上的各种服务。

我正在寻找service.controller,并且已成功通过按钮事件停止和启动各种服务,但现在我正在尝试找出一种方法将服务状态返回到文本框并查询服务状态每个10秒钟左右,我觉得我正在撞砖墙。

有没有人有任何提示或见解?

谢谢!

2 个答案:

答案 0 :(得分: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
        }
    }

答案 1 :(得分: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

干杯  演进