在.Net中监控Processes和Threads(2)
发表于:2007-06-30来源:作者:点击数:
标签:
The Code We use a ListView control in our application to display process information. The InitializeListView method adds column headers, their names and sizes to the ListView control. We@#ll see this method in a moment. A row in a ListView
The Code
We use a ListView control in our application to display process information. The InitializeListView method adds column headers, their names and sizes to the ListView control. We@#ll see this method in a moment.
A row in a ListView control is represented as a ListViewItem. To add a row to the ListView, we need to create an object of a ListViewItem class, call the ListView.Items.Add method, and then pass ListViewItem as an argument.
// Add Item to the list view
ListViewItem item = new ListViewItem(str, 0);
listView1.Items.Add(item);
InitializeListView() Method
This method adds column headers, names, and sizes, and sets other column properties. The Add method of ListViewColumnCollection adds a column header to the control. This method takes the name of the column, the size, and the alignment as arguments.
// Initializes ListView
private void InitializeListView()
{
// Add ListView Column Headers
listView1.Columns.Add("Process", 70, HorizontalAlignment.Left);
listView1.Columns.Add("Proc ID", 70, HorizontalAlignment.Left);
listView1.Columns.Add("Priority", 70, HorizontalAlignment.Left);
listView1.Columns.Add("Physical Mem(KB)", 90, HorizontalAlignment.Left);
listView1.Columns.Add("Virtual Mem(KB)", 90, HorizontalAlignment.Left);
listView1.Columns.Add("Start Time", 150, HorizontalAlignment.Left);
}
FillThreadView() Method
The FillThreadView method is the method that reads all the processes, and fills the list box with process information.
// Initializes ListView
private void FillThreadView()
{
string [] str = new String[6];
// Get all the running processes on the system
procs = Process.GetProcesses();
nProcessCount = procs.Length;
textBox1.Text = nProcessCount.ToString();
foreach(Process proc in procs)
{
// Physical Mem in KB
long physicalMem = proc.WorkingSet/1024;
long virtualMem = proc.VirtualMemorySize/1024;
str[0] = proc.ProcessName.ToString();
str[1] = proc.Id.ToString();
str[2] = proc.BasePriority.ToString();
str[3] = physicalMem.ToString();
str[4] = virtualMem.ToString();
str[5] = proc.StartTime.ToString();
// Add Item to the list view
ListViewItem item = new ListViewItem(str, 0);
listView1.Items.Add(item);
}
}
Start Button
The Start Process button let us browse our machine directory, and pick an .exe program we want to launch. Here we use Process.Start(filename) to start a process.
// Start Process
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Open a Program" ;
fdlg.InitialDirectory = @"c:" ;
fdlg.Filter = "Exe files (*.exe)|*.*|All files (*.*)|*.*" ;
fdlg.FilterIndex = 2 ;
fdlg.RestoreDirectory = true ;
if(fdlg.ShowDialog() == DialogResult.OK)
{
Process.Start(fdlg.FileName);
}
}
Kill Process
The Kill Process button aborts the selected process in the list. ListView@#s SelectedItems property returns the selected row. We call the Process.Kill method to kill a process.
// Kill Process
private void button2_Click(object sender, System.EventArgs e)
{
try
{
ListViewItem li = listView1.SelectedItems[0];
string str = listView1.SelectedItems[0].SubItems[1].Text;
nCurProcId = Convert.ToInt32(str);
for ( int i=0; i<nProcessCount; i++)
{
if ( procs[i].Id == nCurProcId )
{
procs[i].Kill();
return;
}
}
listView1.Items.Remove(li);
}
catch (Exception exp)
{
Console.WriteLine (exp.Message);
return ;
}
}
Refresh Button
The Refresh button refreshes the processes information in the list view, which calls the RefreshList method. The RefreshList method reloads the process information.
// Refresh
private void button3_Click(object sender, System.EventArgs e)
{
RefreshList();
}
protected void RefreshList ()
{
listView1.Clear();
InitializeListView();
FillThreadView();
}
Thread Info Button
The Thread Info button launches a new form, which displays information about threads for the selected process in the listview.
// Thread Info
private void button4_Click(object sender, System.EventArgs e)
{
ListViewItem li = listView1.SelectedItems[0];
string str = listView1.SelectedItems[0].SubItems[1].Text;
int nCurProcId = Convert.ToInt32(str);
Form2 frm = new Form2();
frm.DisplayForm(nCurProcId);
}
The other boxes on the form:
Total Processes: Displays the total number of processes running on the machine.
Auto Refresh: If we check the Auto Refresh check box, our application refreshes the process list and the data every second.
The Thread Information Form
Form2 is a Thread Monitor. This displays the total threads running corresponding to a given process, and returns their statistics such as ID, Current Priorities, thread state, and start time.
The ProcessThread Class
Use ProcessThread to get information about a thread that is currently running on the system. Basically, a process can have one or more threads and the code, data, and other resources of a program in memory. The major ProcessThread class properties are described in the following table, which we@#re going to use in our program later.
The ProcessThread Class Properties
BasePriority, CurrentPriority
Base and current priorities of a thread.
Id
Thread ID.
PriorityLevel
Priority level of the thread.
PrivilegedProcessorTime
Amount of time that a thread has spent running.
StartAddress
Address of the function that started this thread.
StartTime
Thread starting time.
ThreadState
Current state of a thread.
TotalProcessorTime
Total amount of time thread has spent using the processor.
UserProcessorTime
Amount of time a thread has spent running code inside the application.
The DisplayForm Method
The DisplayForm method shows the form and calls the FillThreadList method. We@#ll discuss this method in a moment.
// Fills list with all available threads and other info for a process
public void DisplayForm ( int nProcID )
{
procId = nProcID;
this.Show();
m_Threads = GetThreads(nProcID);
FillThreadList(nProcID );
}
The InitializeThreadList Method
The InitializeThreadList method initializes list view column headers. Its pretty similar to what we@#ve seen above.
private void InitializeThreadList()
{
// Add ListView Column Headers
threadListView.Columns.Add("ID", 50, HorizontalAlignment.Left);
threadListView.Columns.Add("Priority", 70, HorizontalAlignment.Left);
threadListView.Columns.Add("Base Priority", 70, HorizontalAlignment.Left);
threadListView.Columns.Add("Tot Proc Time", 90, HorizontalAlignment.Left);
threadListView.Columns.Add("State", 90, HorizontalAlignment.Left);
threadListView.Columns.Add("Start Time", 150, HorizontalAlignment.Left);
threadListView.Columns.Add("User Processor Time", 150, HorizontalAlignment.Left);
}
The FillThreadList Method
The main functionality is written in the FillThreadList method. The Process.Threads property of a process returns all threads corresponding to a process in the form of a ProcessThreadCollection. The ProcessThreadCollection is a collection of threads.
protected void FillThreadList ( int nProcID )
{
string [] str = new String[7];
m_Threads = GetThreads(nProcID);
ProcessThreadCollection threads;
Process proc;
proc = Process.GetProcessById(nProcID);
// Read the Process.Threads property.
threads = proc.Threads;
// Read desired ProcessThread property.
for ( int i=0; i<threads.Count; i++)
{
str[0] = threads[i].Id.ToString();
str[1] = threads[i].CurrentPriority.ToString();
str[2] = threads[i].BasePriority.ToString();
str[3] = threads[i].TotalProcessorTime.ToString();
str[4] = threads[i].ThreadState.ToString();
str[5] = threads[i].StartTime.ToString();
str[6] = threads[i].UserProcessorTime.ToString();
// Add Item to the list view
ListViewItem item = new ListViewItem(str, 0);
threadListView.Items.Add(item);
}
textBox1.Text = m_Threads.Count.ToString();
}
Summary
In Microsoft@#s .NET Framework Library, the System.Diagnostics namespace contains classes to work with system processes and threads. This namespace also provides classes that allow us to debug and trace our code. In this article, we covered the Process, Threads, and ProcessThread classes to create a thread and process monitoring application.
原文转自:http://www.ltesting.net