【发布时间】:2020-02-09 16:41:35
【问题描述】:
我正在创建一个程序,该程序应在初始子进程之后监视所有子进程。
我正在使用来自流程扩展的 ProcessExtensions.GetProcess 函数来执行此操作,例如:
Dim counter
counter = 0
Dim pr2 = ProcessExtensions.GetProcesses.ToList()
Console.WriteLine(pr2.Count)
For Each pr3 As Process In pr2
counter = counter + 1
Dim parentpr As Process = ProcessExtensions.Parent(pr3) '' <- problem right here
If parentpr IsNot Nothing Then
Console.WriteLine(counter & " " & pr3.Id & " " & pr3.ProcessName & " " & pr3.StartTime & " " & parentpr.Id)
End If
Next
Console.ReadKey()
问题是,这太慢了,检查 windows 10 上的每个进程大约需要半秒,平均有超过 200 个进程,它不允许我检查子进程是否有效启动。
我考虑过创建一个带有开始日期的过滤器,但该过滤器也会循环遍历所有进程,并且无法足够快地提供结果。
同时tasklist 或wmic process get 在命令行上提供即时结果,但会迫使我重新编写所有代码。
是否可以立即监控 Windows 10 上的进程何时启动?
也欢迎其他想法。
我是 VB 新手,在此先感谢您的帮助。
编辑: 问题是获取 ParentID。我正在使用一个自定义的 ProcessExtensions 模块来获取它,但它有点慢。
Public NotInheritable Class ProcessExtensions
Inherits Process
Public Sub New()
End Sub
Private Shared Function FindIndexedProcessName(ByVal pid As Integer) As String
Try
Dim processName = Process.GetProcessById(pid).ProcessName
Dim processesByName = Process.GetProcessesByName(processName)
Dim processIndexdName As String = Nothing
For index As Integer = 0 To processesByName.Length - 1
processIndexdName = If(index = 0, processName, Convert.ToString(processName) & "#" & index)
Dim processId = New PerformanceCounter("Process", "ID Process", processIndexdName)
If CInt(processId.NextValue()).Equals(pid) Then
Return processIndexdName
End If
Next
Return processIndexdName
Catch ex As ArgumentException
Return Nothing
End Try
End Function
Private Shared Function FindPidFromIndexedProcessName(ByVal indexedProcessName As String) As Process
Dim parentId = New PerformanceCounter("Process", "Creating Process ID", indexedProcessName)
Try
Return Process.GetProcessById(CInt(parentId.NextValue()))
Catch ex As Exception
Return Nothing
End Try
End Function
Public Function Parent() As Process
Return FindPidFromIndexedProcessName(FindIndexedProcessName(Me.Id))
End Function
Public Shared Function Parent(ByVal pr As Process) As Process
Return FindPidFromIndexedProcessName(FindIndexedProcessName(pr.Id))
End Function
End Class
【问题讨论】:
-
我认为您正在使用自定义
ProcessExtensions模块。你也应该添加它。 -
只写这段代码
Dim pr = ProcessExtensions.GetProcesses.ToList()需要多长时间? -
我问是因为我认为你的问题不在于获取进程列表只是想确保
-
也许您想测试 WMI 的 Win32_Process。查询被缓存。
-
请检查一下:
Dim x = Process.GetProcesses.ToList()或者简单地说这应该可以工作dim x = Process.GetProcesses
标签: vb.net process windows-10-desktop