繁体中文
设为首页
加入收藏
当前位置:.Net技术首页 >> Asp.Net开发 >> 在.Net中监控Processes和Threads(1)

在.Net中监控Processes和Threads(1)

2007-07-15 08:00:00  作者:  来源:互联网  浏览次数:0  文字大小:【】【】【
简介:A process is an instance of a running application on a system. A process itself is nothing besides memory address space. Besides the space, a process also owns resources including files, dynamic a...

A process is an instance of a running application on a system. A process itself is nothing besides memory address space. Besides the space, a process also owns resources including files, dynamic and virtual memory allocations, and threads. Each process has a unique ID. For a process to accomplish anything, it must own thread(s). Each process has at least one main thread, and can have any number of secondary threads, also known as worker threads.

A thread is a path of execution that executes some part of code in a predefined manner. A thread executes this code in a processes address space. Each thread has a unique ID, and allocates its own resources such as CPU registers and stack.

In this article, we will discuss how to return all the available processes on a machine, and all the threads corresponding to a process. The sample application we develop shows the total number of running processes, their IDs, and corresponding information such as physical and virtual memory, starting time, etc. This program also lets us monitor available threads, information that is not available in Windows Task Manager.

System.Diagnostics Namespace

In the .NET Framework, the System.Diagnostics namespace defines classes that allow us to debug and trace applications, read and write event logs, and monitor processes and system performance using performance counters. The major classes include Debug, Counter, EventLog, Process, ProcessThread, StackTrace, and Trace.

A discussion of all these classes is out of the scope of this article - we will cover only the Process class and its related classes.

The Process Class

In .NET, the Process class enables us to start and stop processes on a local or a remote machine. The Process class also enables us to monitor system resources, such as all running processes, their ID, threads corresponding to process IDs, and threads related to each process. It also lets us monitor resources allocated by processes and threads, such as physical memory, paged memory, virtual memory, peak paged memory, and peaked virtual memory size.

Creating an instance and get all running Processes

There are two ways to create an instance of a Process class. Either we call the Process constructor followed by the Start method to start a process, or we can directly call the GetProcesses method, which returns all the running processes on a machine. The Process class constructor doesn't take any parameters. See the following definition of the Process constructor.

Using System.Diagnostics;

public Process();

Process prCSS = new Process();

prCSS.Start();

OR:

Process[] procs = Process.GetProcesses();

Get all the running processes

The GetProcesses method of the Process class returns all the running processes on a machine. The following code returns all the processes and writes to the system console.

Process[] procs = Process.GetProcesses();

foreach(Process proc in procs)

{

Console.Write("Process Name:"+proc.ProcessName +",");

}

Get Process Names and Process IDs

We use the Process Name and Id properties to get process name and process IDs of the processes:

Process[] procs = Process.GetProcesses();

foreach(Process proc in procs)

{

Console.Write("Process Name:"+proc.ProcessName +",");

Console.Write("Process Id:"+ proc.Id.ToString()+",");

}

Get Process Resources Information

By using the Process class we can even discover resource data such as physical and virtual memory for a process. The WorkingSet property returns the physical memory and VirtualMemorySize returns the virtual memory, in bytes, for a process.

Process[] procs = Process.GetProcesses();

foreach(Process proc in procs)

{

Console.Write("Virtual Memory Size:"+ proc.VirtualMemorySize.ToString()+",");

Console.Write("Physical Memory:"+ proc.WorkingSet.ToString()+",");

proc.WorkingSet.ToString()+",");

}

}

Get Process Time

We discover the startup time of a process, by using the StartTime property.

Process[] procs = Process.GetProcesses();

foreach(Process proc in procs)

{

string stratTime = proc.StartTime.ToString();

string threadPriority = proc.BasePriority.ToString();

}

Get Thread Priority

We can even gather other information, such as the priority of a thread, with the BasePriority property:

Process[] procs = Process.GetProcesses();

foreach(Process proc in procs)

{

string threadPriority = procList[i].BasePriority.ToString();

}

Return all the threads corresponding to a process

We use the Threads property to return all the running threads corresponding to a process:

Public ProcessThread [] Threads();

Return Maximum and Minimum physical memory

We use MaxWorkingSet and MinWorkingSet members to get the maximum and minimum values of a working set.

Getting Processor Time

the UserProcessorTime and TotalProcessorTime properties return the time that the process has spent running since it started in this application, and usage time of the CPU respectively.

Start a Process

We can use the Start method of the Process class to start a method. The Start method takes one parameter, the file name of the .exe we want to start:

Process.Start(FileName);

We can even use the GetProcessByName and GetProcessById methods to get a process by using names and IDs. Both of the methods return a Process type.

Killing a Process

The Kill method is used to abort a process. We must ensure that procs is the process we want to abort. As discussed earlier, procs is an array of Process types.

Process[] procs = Process.GetProcesses();

..... ...

procs[i].Kill();

Or:

Process.Kill();

Freeing Resources

The Close method of the Process class frees all resources associated with a process.

procs[i].Close();

Be careful when using the Kill method to terminate a process. The Kill method causes abnormal termination of an application and should be used carefully. There are chances of losing data if we call the Kill method. However using the Close method is safe. The Close method makes sure that the process has finished its message loop, finished its job and then requests termination. There may be the possibility that Close will ask user to close an application.

Sample Program:

This simple program displays all the running processes and their corresponding information.

Listing ProcInfo.cs Sample Code

using System;

using System.Diagnostics;

namespace ProcessInfo

{

///

/// Summary description for Class1.

///

class Class1

{

static void Main(string[] args)

{

Process[] procs = Process.GetProcesses();

foreach(Process proc in procs)

{

// Process Name

Console.WriteLine("Process Name:"+proc.ProcessName +",");

// Process Start Time

Console.WriteLine("Start Time:"+ proc.StartTime+",");

// Process ID

Console.WriteLine("Process Id:"+ proc.Id.ToString()+",");

// Process Virtual Memory

Console.WriteLine("Virtual Memory Size:"+ proc.VirtualMemorySize.ToString()+",");

// Process Physical Memory

Console.WriteLine("Physical Memory:"+ proc.WorkingSet.ToString()+",");

// Other resources

Console.WriteLine("Paged Memory:"+ proc.PagedMemorySize.ToString()+",");

Console.WriteLine("Peakworkingset Memory:"+ proc.PeakWorkingSet.ToString()+",");

Console.WriteLine("Total Processor Time:"+ proc.TotalProcessorTime.ToString()+",");

Console.WriteLine("Peak virtual Memory:"+ proc.PeakVirtualMemorySize.ToString()+",");

Console.WriteLine("User Processor Time:"+ proc.UserProcessorTime.ToString()+",");

Console.WriteLine("Prev. Processor Time:"+ proc.PrivilegedProcessorTime.ToString()+",");

Console.WriteLine("============================================");

}

}

}

}

The ProcessThread Class

The ProcessThread class represents a Win32 thread. This class can be used to gather information about a thread such as thread ID, starting time of a thread, base and current priorities, address of the function called when the thread was started, and more.

Get threads

We use the Threads member of the ProcessThreads class to return an array containing all the threads for that process:

public ProcessThread [] Threads();

ProcessThread [] threads = proc.Threads;

Returning a thread ID

Every thread has a unique ID. We can call the Id property of the thread to get the unique ID of a thread.

private ProcessThread [] m_Threads;

string str = m_Threads[i].Id.ToString();

Return the priority of a Thread

A process has two types of priorities - base and current. The base priority is computed by combining the process priority class with the priority level of the associated thread. The base priority of the thread changes depending on the time and resource allocation by the Operating System. The current priority might be different to the base priority depending on how the OS schedules the thread.

The BasePriority and CurrentPriority properties return the base and the current priority of a thread.

Strstr = m_Threads[i].BasePriority.ToString();

Strstr = m_Threads[i].CurrentPriority.ToString();

How Much Time Has The Thread Spent Running?

You can also find out how much time a thread has spent using the CPU or running in the current process by using UserProcessorTime, TotalProcessorTime, and PrivilegedProcessorTime properties.

str = m_Threads[i].UserProcessorTime.ToString();

str = m_Threads[i].TotalProcessorTime.ToString();

Thread State

We can use the ThreadState property to find out the current state of the thread - whether it is Initialized, Running, Waiting, etc. This property returns the ThreadState enum type:

Strstr = m_Threads[i].ThreadState.ToString();

The ThreadState enum members are described in the following table:

Member

Description

Initialized

Thread has been initialized, but has not started yet.

Ready

Thread is in ready state.

Running

Thread is running.

Standby

Thread is in standby state.

Terminated

Thread has exited.

Transition

Thread is transitioning between states.

Unknown

Thread state is unknown.

Wait

Thread is waiting.

The Sample Project - The ProcessMonitor

Now it's time to implement the above concepts in an application. This application lets us start or abort a process, and displays information such as the name of the processes running on the machine, their IDs, physical and virtual memory usage, and their priorities. It looks something like this:

责任编辑:admin
相关文章