相当于windows系统中的任务管理器,功能是通过系统的API实现的本机的监视,代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Data;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Demo
{
/// <summary>
/// 检测内存信息
/// </summary>
public class CheckMemoryInfo
{
[StructLayout(LayoutKind.Sequential)]
public struct MEMORYSTATUSEX
{
public int dwLength;
public int dwMemoryLoad;
public long ullTotalPhys; //内存总数
public long ullAvailPhys; //可用物理内存
public long ullTotalPageFile; //分页数据
public long ullAvailPageFile; //未分页数据
public long ullTotalVirtual; //虚拟内存总数
public long ullAvailVirtual;//可用虚拟内存总数
public long ullAvailExtendedVirtual;//扩展虚拟内存
}
[DllImport("kernel32.dll")]
public static extern void GlobalMemoryStatusEx(ref MEMORYSTATUSEX stat);
/// <summary>
/// 可用物理内存
/// </summary>
/// <returns>long</returns>
public long GetAvailPhys()
{
MEMORYSTATUSEX memInfo = new MEMORYSTATUSEX();
memInfo.dwLength = (int)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
GlobalMemoryStatusEx(ref memInfo);
return memInfo.ullAvailPhys;
}
/// <summary>
/// 内存总数
/// </summary>
/// <returns>long</returns>
public long GetullTotalPhys()
{
MEMORYSTATUSEX memInfo = new MEMORYSTATUSEX();
memInfo.dwLength = (int)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
GlobalMemoryStatusEx(ref memInfo);
return memInfo.ullTotalPhys;
}
/// <summary>
/// 虚拟内存总数
/// </summary>
/// <returns>long</returns>
public long GetTotalVirtual()
{
MEMORYSTATUSEX memInfo = new MEMORYSTATUSEX();
memInfo.dwLength = (int)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
GlobalMemoryStatusEx(ref memInfo);
return memInfo.ullTotalVirtual;
}
/// <summary>
/// 可用虚拟内存总数
/// </summary>
/// <returns>long</returns>
public long GetAvailVirtual()
{
MEMORYSTATUSEX memInfo = new MEMORYSTATUSEX();
memInfo.dwLength = (int)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
GlobalMemoryStatusEx(ref memInfo);
return memInfo.ullAvailVirtual;
}
/// <summary>
/// 获取DataTable占用内存数
/// </summary>
/// <param name="dt">DataTable</param>
/// <returns>long类型,单位字节</returns>
public long GetDataTableMemoryInfo(DataTable dt)
{
if (dt == null)
{
return 0;
}
MemoryStream ms = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, dt);
ms.Position = 0;
return ms.Length;
}
}
}