C#监控内存占用数据
作者:oschina.ne 来源:oschina.net 发布时间:2014-05-06 查看数:63884
利用C#来监控当前程序的内存占用信息,并写入日志!
string LogAddress = Environment.CurrentDirectory + "\\Log.log";
//需要引用命名空间 System.Diagnostics;
//获取当前进程
Process currentProcess = Process.GetCurrentProcess();
// 如果获取指定进程,可以使用使用GetProcessesByName或者GetProcessById,比如:
// Process currentProcess = Process.GetProcessById(11980);
// Process currentProcess = Process.GetProcessesByName("QQ.exe");
using (StreamWriter sw = new StreamWriter(LogAddress, true))
{
sw.Write(DateTime.Now.ToString());
sw.Write("\r\n进程标识: ");
sw.Write(currentProcess.Id.ToString());
sw.Write("\r\n进程名称: ");
sw.Write(currentProcess.ProcessName.ToString());
sw.Write("\r\n占用内存: ");
sw.Write(currentProcess.WorkingSet64 / 1024);
sw.Write("KB");
sw.Write("\r\n线程数量: ");
sw.Write(currentProcess.Threads.Count.ToString());
}
如果要查询所有进程的占用情况,遍历所有进程即可:
Process[] processList = Process.GetProcesses();
long n = 0;
for (int i = 0; i < processList.Length; i++)
{
n += processList[i].WorkingSet64;
}
using (StreamWriter sw = new StreamWriter(LogAddress, true))
{
sw.Write(DateTime.Now.ToString());
sw.Write("\r\n总进程数: ");
sw.Write(processList.Length.ToString());
sw.Write("\r\n占用内存: ");
sw.Write(n / 1024);
sw.Write("KB");
}
原文作者:北风其凉 原文地址:http://www.oschina.net/code/snippet_1425762_35128