VB.NET / WMI - 实时Windows服务监控?

时间:2013-01-08 20:21:59

标签: vb.net timer wmi monitoring

因此我的工作中有一个应用程序可以将多个Windows服务安装到服务器上。作为一个辅助项目,我被要求制作一个简单的GUI,它将列出这些服务,并在每个服务的名称旁边加上一个“灯”(带有红色或绿色圆点的图片框)。这个想法是,如果这些服务停止运行,“光”将从绿色变为红色。

我已经构建了GUI部件,我可以查询远程服务器的服务,然后将其与我感兴趣的数组进行比较,并将每个服务旁边的“light”设置为绿色/红色,具体取决于服务州。我要挂断的部分是如何实时监控这些服务?目前,我在Form_Load事件中只有以下代码:

Dim myConnectionOptions As New System.Management.ConnectionOptions
With myConnectionOptions
    .Impersonation = System.Management.ImpersonationLevel.Impersonate
    .Authentication = System.Management.AuthenticationLevel.Packet
End With

Try

    Dim myManagementScope As System.Management.ManagementScope
    myManagementScope = New System.Management.ManagementScope("\\" & SERVERNAME & "\root\cimv2", myConnectionOptions)
    myManagementScope.Connect()

    Dim query As New Management.ObjectQuery("SELECT * FROM Win32_Service")
    Dim searcher As New Management.ManagementObjectSearcher(myManagementScope, query)
    Dim i As Integer = 0

    For Each queryObj As Management.ManagementObject In searcher.Get()
        For Each service As String In arrServices
            If queryObj("DisplayName").Equals(service) Then
                If queryObj("State").Equals("Stopped") Then
                    arrLights(i).Image = My.Resources.redlight
                End If
                i += 1
            End If
        Next
    Next

Catch err As Management.ManagementException
    MessageBox.Show("WMI query failed with the following error: " & err.Message)
Catch unauthorizedErr As System.UnauthorizedAccessException
    MessageBox.Show("Authentication error: " & unauthorizedErr.Message)
End Try

重复执行此代码的简单计时器是最好的方法,还是有更优雅的解决方案?我在VB.NET和WMI方面有一点经验,但在任何类型的实时监控活动中都没有这样的经验。

1 个答案:

答案 0 :(得分:2)

首先,我会把它放到一个线程中,这样即使你的连接超时你也不要冻结你的UI,然后我会使用自定义等待计时器而不是内置的,因为交叉线程可能会很痛苦。 / p>

等待计时器:

Public Sub Wait(ByVal wait_time As Integer)
  Dim time As Date
  time = Now.AddMilliseconds(wait_time)
  Do While time > Now
     Application.DoEvents()
  Loop
End Sub

线程示例:

Private services_check As Thread
private sub form1_load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
services_check = new thread(AddressOf 'Current code in a public sub')
services_cheack.IsBackground = True
Services_check.start()

它可能不是最优雅的解决方案,但它是如何做到的,至于你当前的代码我很抱歉我不太了解远程连接来帮助你。