Free mag vol1 | Page 687

CHAPTER 17  PROCESSES, APPDOMAINS, AND OBJECT CONTEXTS try { theProc = Process.GetProcessById(pID); } catch(ArgumentException ex) { Console.WriteLine(ex.Message); return; } // List out stats for each thread in the specified process. Console.WriteLine("Here are the threads used by: {0}", theProc.ProcessName); ProcessThreadCollection theThreads = theProc.Threads; } foreach(ProcessThread pt in theThreads) { string info = string.Format("-> Thread ID: {0}\tStart Time: {1}\tPriority: {2}", pt.Id , pt.StartTime.ToShortTimeString(), pt.PriorityLevel); Console.WriteLine(info); } Console.WriteLine("************************************\n"); As you can see, the Threads property of the System.Diagnostics.Process type provides access to the ProcessThreadCollection class. Here, you are printing out the assigned thread ID, start time, and priority level of each thread in the process specified by the client. Now, update your program’s Main() method to prompt the user for a PID to investigate, as follows: static void Main(string[] args) { ... // Prompt user for a PID and print out the set of active threads. Console.WriteLine("***** Enter PID of process to investigate *****"); Console.Write("PID: "); string pID = Console.ReadLine(); int theProcID = int.Parse(pID); } EnumThreadsForPid(theProcID); Console.ReadLine(); When you run your program, you can now enter the PID of any process on your machine, and see the threads used in the process. The following output shows the threads used by PID 108 on my machine, which happens to be hosting Microsoft Internet Explorer: ***** Enter PID of process to PID: 108 Here are the threads used by: -> Thread ID: 680 Start -> Thread ID: 2040 Start 630 investigate ***** iexplore Time: 9:05 AM Time: 9:05 AM Priority: Normal Priority: Normal