vb.net 通过进程 ID 获取进程的 CPU 使用率
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14802787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get CPU Usage for Process by Process ID
提问by Brady
I have a process ID, and I need to get the CPU usage a.k.a % Processor Timeof the process.
我有一个进程 ID,我需要获取进程的 CPU 使用率,也就是% Processor Time。
For example, here is a simple function to return the CPU usage of AppName:
例如,这里有一个简单的函数来返回 AppName 的 CPU 使用率:
Private Function Get_CPU_Usage(AppName as String)
Dim AppCPU As New PerformanceCounter("Process", "% Processor Time", AppName, True)
Return AppCPU.NextValue
End Function
It might be wrong but it's just an example.
这可能是错误的,但这只是一个例子。
I need to do something like this:
我需要做这样的事情:
Private Function Get_CPU_Usage(ProcessID as Integer)
Dim AppCPU As New PerformanceCounter("Process", "% Processor Time", ProcessID, True)
Return AppCPU.NextValue
End Function
Note ProcessID vs AppName. I have multiple processes running with the same name; each application's PID is stored in my program. I know I can iterate through...
注意 ProcessID 与 AppName。我有多个运行同名的进程;每个应用程序的 PID 都存储在我的程序中。我知道我可以迭代...
PerformanceCounter("Process", "ID Process", AppName, True)
to find the process name, like app, app#1, app#2, but it seems inefficient and sloppy.
找到进程名称,如app、app#1、app#2,但看起来效率低下且马虎。
What is the recommended procedure here?
这里推荐的程序是什么?
回答by Brady
Thanks to Hans Passantfor the link to the answer in C# form, here is the VB.net function converted from Performance Counter by Process I instead of name:
感谢Hans Passant以 C# 形式提供答案的链接,这是由 Process I 而不是 name从Performance Counter转换的 VB.net 函数:
Public Shared Function GetProcessInstanceName(ByVal PID As Integer) As String
Dim cat As New PerformanceCounterCategory("Process")
Dim instances() = cat.GetInstanceNames()
For Each instance In instances
Using cnt As PerformanceCounter = New PerformanceCounter("Process", "ID Process", instance, True)
Dim val As Integer = CType(cnt.RawValue, Int32)
If val = PID Then
Return instance
End If
End Using
Next
End Function

