0

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

我已经构建了 GUI 部分,我可以查询远程服务器的服务,然后将其与我感兴趣的数组进行比较,并根据服务状态将每个服务旁边的“灯”设置为绿色/红色。我挂断的部分是如何实时监控这些服务?目前,我在 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 方面有一点经验,但在任何类型的实时监控活动中都没有这样的经验。

4

1 回答 1

2

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

等待计时器:

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()

它可能不是最优雅的解决方案,但它是我将如何做到的,至于您当前的代码,对不起,我对远程连接的了解不够,无法帮助您。

于 2013-01-09T13:12:35.453 回答