如何创建一个可以等待多个进程退出的函数?

How to create a function that can wait for multiple processes to exit?

我正在创建一个 windows 服务,该服务将为我要监视的特定进程写入所有开始时间和退出时间。问题是当我试图监视等待退出的进程时,我不知道如何等待多个进程退出。下面是我编写进程开始时间的代码。

Try
    Using regkey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey("SOFTWARE\MonitoringApplication\Login", RegistryKeyPermissionCheck.Default)
        childrenID = regkey.GetValue("Login User").ToString
    End Using
    If childrenID.Equals("admin") Then
    Else
        Dim connection As New SqlConnection("Server=DESKTOP-FTJ3EOA\SQLEXPRESS;Initial Catalog=MonitorDB;User ID = admin; Password = admin")
        Dim command As New SqlCommand("SELECT  App.ApplicationName FROM App INNER JOIN ChildrenApplication ON App.ApplicationID = ChildrenApplication.ApplicationID WHERE ChildrenID = @a", connection)
        command.Parameters.Add("@a", SqlDbType.VarChar).Value = childrenID
        Dim adapter As New SqlDataAdapter(command)
        Dim table As New DataTable()
        adapter.Fill(table)

        Using sw As StreamWriter = New StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\MonitoringApplication.txt", True)

            For Each row As DataRow In table.Rows
                p = Process.GetProcessesByName(row.Item(0))
                Using myprocess = New Process
                    If p.Count > 0 Then
                        myprocess.StartInfo.FileName = row.Item(0)
                        myprocess.EnableRaisingEvents = True
                        sw.WriteLine(row.Item(0) + "running")

                    End If
                End Using
            Next row
        End Using

        Const SLEEP_AMOUNT As Integer = 100
        Do While Not eventHandled
            elapsedTime += SLEEP_AMOUNT
            If elapsedTime > 30000 Then
                Exit Do
            End If
            Thread.Sleep(SLEEP_AMOUNT)
        Loop
    End If
Catch ex As Exception
    Using sw As StreamWriter = New StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\MonitoringApplication.txt", True)
        sw.WriteLine(ex)
    End Using
End Try

Private Sub myProcess_Exited(ByVal sender As Object, ByVal e As System.EventArgs) Handles myProcess.Exited
    eventHandled = True
    Using sw As StreamWriter = New StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\MonitoringApplication.txt", True)
        sw.WriteLine("Exited")
    End Using
End Sub

有什么方法可以监控多个进程退出?提前致谢。

您现在正在使用 Process.GetProcessesByName() 检索 运行 个进程的数组,如果有的话。
您可以使用返回的进程数组并订阅每个进程的 Exited 事件以记录数组中任何进程的退出时间。

设置 EnableRaisingEvent 是引发 Exited 事件所必需的,但您还需要订阅事件,使用 AddHandler 以及方法或 Lambda 的地址:

AddHandler [Process].Exited, AddressOf [Handler]
' or 
AddHandler [Process].Exited, Sub() [Lambda]

此方法接受一个进程名称和一个文件的路径,该文件用于存储进程的名称及其在引发 Exited 事件时的退出时间。

如果您当前的循环:

For Each row As DataRow In table.Rows
    '(...)
Next

您可以插入对此方法的调用:

For Each row As DataRow In table.Rows
    SubscribeProcExit(row.Item(0), Path.Combine(Application.StartupPath, "MonitoringApplication.txt"))
Next

如果日志文件没有退出,每次其中一个进程退出时都会创建它并添加一个新行,记录 Process.ProcessNameProcess.ExitTime.
请注意,row.Item(0) 必须包含进程的友好名称。例如,notepad.exe 必须被引用为 "notepad"

Private Sub SubscribeProcExit(processName As String, fileName As String)
    Dim processes As Process() = Process.GetProcessesByName(processName)
    If processes.Length = 0 Then Return
    For Each p As Process In processes
        p.EnableRaisingEvents = True
        AddHandler p.Exited,
            Sub()
                Using sw As StreamWriter = File.AppendText(fileName)
                    sw.WriteLine($"Process: {p?.ProcessName}, Exit Time: {p?.ExitTime}")
                    p?.Dispose()
                End Using
            End Sub
    Next
End Sub