Mohsen-Unique
Mohsen-Unique

Reputation: 13

Get count of open Thread of process in c#

I want get count of thread that open by process that i run from my app to run app i use this code

p.StartInfo = new ProcessStartInfo(Application.StartupPath + @"\bin\childApp.exe", parametr);
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();

i want know how many thread opened by this app i run it i use this code this work but has very big CPU usage when use it every second

private int GetThread(string AppId)
        {
            try
            {
                string queryString = "select ThreadCount from Win32_Process WHERE ProcessId='" + AppId + "'";

                SelectQuery query = new SelectQuery(queryString);
                ManagementScope scope = new System.Management.ManagementScope(@"\\.\root\CIMV2");

                ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
                ManagementObjectCollection processes = searcher.Get();

                int result = 0;
                foreach (ManagementObject mo in processes)
                {
                    result = Convert.ToInt32(mo["ThreadCount"]);
                    break;
                }

                return result;
            }
            catch
            {
                return 0;
            }
        } 

is there any other way to do this?

Upvotes: 1

Views: 353

Answers (1)

Bogdan
Bogdan

Reputation: 484

p.Refresh();
var threadCount = p.Threads.Count;

Upvotes: 2

Related Questions