获取流程所有者的CPU使用率为100%

时间:2017-03-07 15:12:08

标签: c# window

我创建了一个小型控制台应用程序,以获取具有特定名称的所有进程,并且我希望获得具有最高CPU使用率的进程。

到目前为止,它的工作正常。当我检索具有最高CPU使用率的进程的所有者时,应用程序很快就到了这一点。当此特定进程需要大约90-100%的CPU使用率时,检索所有者大约需要2分钟。如果只有"睡觉"流程,它的速度要快得多。

有人能告诉我一个比我更好的解决方案吗?我已经尝试了一些其他解决方案来获取所有者(即使是在使用GetOwner的stackoverflow上的这个)

[DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle);
    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(IntPtr hObject);

    static void Main(string[] args)
    {
        List<Process> listProcesses = Process.GetProcesses().Where(x => x.ProcessName.Contains("MyProcess")).ToList();
        Dictionary<Process, double> dictUsers = new Dictionary<Process, double>();

        foreach(Process process in listProcesses)
        {
            PerformanceCounter counter = new PerformanceCounter("Process", "% Processor Time", process.ProcessName);
            counter.NextValue();
            Thread.Sleep(1000);
            dictUsers.Add(process, Math.Round(counter.NextValue() / Environment.ProcessorCount, 1));
        }

        dictUsers = dictUsers.OrderByDescending(key => key.Value).ToDictionary(v => v.Key, x => x.Value);

        if(dictUsers.Count > 0)
        {
            string username = string.Empty;

            Process proc = dictUsers.First().Key;
            username = GetProcessUser(proc);

            Console.WriteLine(username);
        }
        else
        {
            Console.WriteLine("No user found");
        }
    }

    private static string GetProcessUser(Process process)
    {
        IntPtr processHandle = IntPtr.Zero;
        try
        {
            OpenProcessToken(process.Handle, 8, out processHandle);
            WindowsIdentity wi = new WindowsIdentity(processHandle);
            string user = wi.Name;
            return user;
        }
        catch
        {
            return null;
        }
        finally
        {
            if (processHandle != IntPtr.Zero)
            {
                CloseHandle(processHandle);
            }
        }
    }

0 个答案:

没有答案