Fork me on GitHub

C# 操作线程的通用类[测试通过]

进程管理就是对服务器性能的管理和协调,在程序的运行角度来看非常重要,也可以根据操作进程的手段,衍生很多实用和智能的功能,以下就是介绍一个自己写的进程通用操作类,功能如下:

1.把ProcessUtility类直接复制到程序中即可实用。

2.调用方法 ex:ProcessUtility.resetProcessByPName("explorer");

代码如下:

 

代码
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

/// <summary>
/// author:Stone_W
/// date:2010.12.20
/// desc:进程管理类
/// </summary>
public class ProcessUtility
{
#region 进程的cpu使用率
/// <summary>
/// 进程的cpu使用率
/// </summary>
/// <param name="processName">进程的名称</param>
/// <returns>string</returns>
public static string GetProcessRate(string processName)
{
string result = String.Empty;
try
{
PerformanceCounter pfc
= new PerformanceCounter(); // 性能计数器
pfc.CategoryName = "Process"; // 指定获取计算机进程信息
pfc.CounterName = "% Processor Time"; // 占有率
pfc.InstanceName = processName; // 指定进程
pfc.MachineName = ".";
result
= Math.Round(pfc.NextValue(), 2) + "%";
}
catch (Exception ex) { }
return result;
}
#endregion

#region 进程内存使用(单位:K)
/// <summary>
/// 进程内存使用(单位:K)
/// </summary>
/// <param name="pcs">进程实体</param>
/// <returns>string</returns>
public static string GetProcessDDR(Process pcs)
{
string result = String.Empty;
try
{
result
= (pcs.PrivateMemorySize / 1000.0).ToString();
}
catch (Exception ex) { }
return result;
}
#endregion

#region 关闭进程
/// <summary>
/// 关闭进程
/// </summary>
/// <param name="pName">进程的名称</param>
/// <returns>bool</returns>
public static bool StopProcessByPName(string pName)
{
bool result = false;
if (!String.IsNullOrEmpty(pName))
{
try
{
Process[] myProcesses
= Process.GetProcesses();
foreach (System.Diagnostics.Process myProcess in myProcesses)
{
if (myProcess.ProcessName.ToUpper() == pName.ToUpper().Trim())
{
myProcess.Kill();
}
}
result
= true;
}
catch (Exception ex) { }
}
return result;

}
#endregion

#region 重新启动进程
/// <summary>
/// 重新启动进程
/// </summary>
/// <param name="pName">进程名称</param>
/// <returns>bool</returns>
public static bool resetProcessByPName(string pName)
{
bool result = false;
if (!String.IsNullOrEmpty(pName))
{
try
{
Process[] myProcesses;
myProcesses
= Process.GetProcessesByName(pName);
foreach (Process myProcess in myProcesses)
{
myProcess.Kill();
}
result
= true;
}
catch (Exception ex) { }
}
return result;
}
#endregion
}

 

 

 

posted @ 2010-12-20 17:01  磊哥|www.javacn.site  阅读(926)  评论(1编辑  收藏  举报