Win32_Process query optimization

1.7k views Asked by At

I am working on a query on Win32_Process to get some info about running processes

ManagementObjectSearcher mSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Process WHERE ProcessID = " + processId);

ManagementObject process = mSearcher.Get().Cast<ManagementObject>().FirstOrDefault();

    if (process != null)
        {
            string[] argList = {string.Empty, string.Empty};
            int returnVal = Convert.ToInt32(process.InvokeMethod("GetOwner", argList));
            Username = returnVal == 0 ? argList[0] : "";
            try
            {
                Description = FileVersionInfo.GetVersionInfo((string) process["ExecutablePath"]);
            }
            catch (Exception)
            {
                Description = "";
            }
        }

This query takes long time, so I am trying to make 3 solutions combination

1- ("SELECT TOP 1 * FROM Win32_Process WHERE ProcessID = " + processId);

But: Not accepted (Invalid query)

2- Using Linq to sql to get the first or default value directly with linq

But: couldn't make it

3-("SELECT TOP 1 ExecutablePath FROM Win32_Process WHERE ProcessID = " + processId);

but assuming that TOP 1 worked, I cannot:

int returnVal = Convert.ToInt32(process.InvokeMethod("GetOwner", argList));

So what is the best solution for this function to be as fast as possible

2

There are 2 answers

0
Konigstiger0x01 On BEST ANSWER

You should use Windows API directly. You could try to use function called NTQuerySystemInformation from NTDLL.dll or higher level kernel32 function using ToolHelp32

Google how to P/Invoke those functions and use them. C# gives you very strong interface for interaction with WinAPI features and you must use it for such tasks.

1
Ivan R. On

You could restrict retriving data with "Handle" and "ExecutablePath".

ManagementObjectSearcher mSearcher = new ManagementObjectSearcher("SELECT Handle, ExecutablePath FROM Win32_Process WHERE ProcessID = " + processId);

With process handle you could call GetOwner method.