因此,在我的工作中,有一个应用程序可以将多个Windows服务安装到服务器上。作为一个辅助项目,我被要求做一个简单的GUI,它将列出这些服务,并在每个服务的名称旁边加上"light“(带有红色或绿色圆点的图片框)。这个想法是,在这些服务停止运行的情况下,“灯”将从绿色变为红色。
我已经构建了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方面有一些经验,但在任何类型的实时监控活动中都没有。
发布于 2013-01-09 21:12:35
首先,我会把它放到一个线程中,这样即使你的连接超时,你也不会冻结你的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()这可能不是最优雅的解决方案,但这是我怎么做的,至于你目前的代码,我很抱歉我对远程连接的了解不够多,无法帮助你。
https://stackoverflow.com/questions/14223368
复制相似问题