I have written a module that gets list of running processes every 250ms for Windows XP and Above. I have tried .Net & WMI way, both of them are very CPU intensive. Both of them do finish within 80ms on my machine. My host process CPU remains above 10 to 14 percentage in either case. I think the Location/ExecutionPath property is the real culprit. Is there a better way to get this information?
Edit1: In my testing - .Net way was more CPU intensive but slightly faster then WMI way. - WMI way was slower but less CPU intensive since it moved the CPU usage to WMI Provider Host
private static int WMIWay()
{
string wmiQueryString = "SELECT ProcessId, ExecutablePath FROM Win32_Process";
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
{
using (var results = searcher.Get())
{
foreach (ManagementObject oReturn in results)
{
if (oReturn["ExecutablePath"] != null)
{
_Processes.Add(new ProcessInfo()
{
ProcessID = (uint)oReturn["ProcessId"],
FilePath = oReturn["ExecutablePath"].ToString(),
});
}
}
return results.Count;
}
}
}
private static int NetWay()
{
var processes = System.Diagnostics.Process.GetProcesses();
foreach (System.Diagnostics.Process runningProcess in processes)
{
if (runningProcess.Id > 4)
{
try
{
_Processes.Add(new ProcessInfo()
{
ProcessID = (uint)runningProcess.Id,
FilePath = runningProcess.MainModule.FileName,
});
}
catch { }
}
}
return processes.Length;
}