c# 如何查看某个程序所占内存

一、需求

      需要查看某个进程的内存占用情况,最好还能给出占用比例。

二、主要内容

      使用Process类可以很轻松的获取某个进程的各种信息,而主机的内存信息则可以通过WMI(Windows Management Instrumentation)获取。

      所需空间:

      System.Diagnostics;   System.Management;

  System.Management 提供对一组丰富的管理信息和管理事件(它们是关于符合 Windows Management Instrumentation (WMI) 基础结构的系统、设备和应用程序的)的访问。 应用程序和服务可以使用从 ManagementObjectSearcher 和 ManagementQuery 派生的类,查询感兴趣的管理信息(例如在磁盘上还剩多少可用空间、当前 CPU 利用率是多少、某一应用程序正连接到哪一数据库等等),这里面当然就包括我们想要的主机的内存信息。

   

[Provider("CIMWin32")]class Win32_PhysicalMemory : CIM_PhysicalMemory
{
  string   BankLabel;
  uint64   Capacity;//内存容量
  string   Caption;
  string   CreationClassName;
  uint16   DataWidth;
  string   Description;
  string   DeviceLocator;
  uint16   FormFactor;
  boolean  HotSwappable;
  datetime InstallDate;
  uint16   InterleaveDataDepth;
  uint32   InterleavePosition;
  string   Manufacturer;
  uint16   MemoryType;
  string   Model;
  string   Name;
  string   OtherIdentifyingInfo;
  string   PartNumber;
  uint32   PositionInRow;
  boolean  PoweredOn;
  boolean  Removable;
  boolean  Replaceable;
  string   SerialNumber;
  string   SKU;
  uint32   Speed;
  string   Status;
  string   Tag;
  uint16   TotalWidth;
  uint16   TypeDetail;
  string   Version;
};
 
不多说上代码:
long totalmem = 0;
System.Management.ManagementObjectSearcher Searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMemory");
foreach (System.Management.ManagementObject wmi in Searcher.Get())
       {
        //内存条累加
         totalmem += (Convert.ToInt64(wmi.GetPropertyValue("Capacity").ToString()) / 1024)//"KB"
       }
这样我们就获得了机器的内存,下面我们再获取我们感兴趣的进程的内存:
   long processmen = 0;
   Process[] process = Process.GetProcessesByName("QQ");
   foreach(Process pro in process)
      processmem += pro.PrivateMemorySize64 / 1024;//PrivateMemorySize已经过时,现在是PrivateMemorySize64

如果想知道当前进程的信息:
    Process process = Process.GetCurrentProcess();
    processmem = (process.PrivateMemorySize64 / 1024);
我们可以select的东西有很多,而且可以from的对象也有很多,这里列举一些:
Win32_BIOS
Win32_ComputerSystem
Win32_Desktop
Win32_Directory
Win32_Processor

参考博客:
http://msdn.microsoft.com/zh-cn/library/System.Management(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/aa394347(VS.85).aspx
http://blog.sina.com.cn/s/blog_476418510100x9xn.html
http://bbs.csdn.net/topics/300040625

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值