c#查看电脑内存

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Management;
using System.Runtime.Serialization.Formatters.Binary;

using RemoteDeploy.Core;
using RemoteDeploy.Core.Attributes;
using RemoteDeploy.CommandHelper;

using Common.Logging;

namespace RemoteDeploy.Commands
{
    [Command(Name = "memoryMonitorCommand", Description = "monitoring memory usage")]
    public class MemoryMonitorCommand
    {
        private const string PROPERTY_CAPACITY = "Capacity";
        private const string PROPERTY_AVAILABLE_BYTES = "AvailableBytes";
        private const string PROPERTY_PROCESS_ID = "ProcessId";
        private const string PROPERTY_PROCESS_NAME = "Name";
        private const string PROPERTY_WORKING_SET_SIZE = "WorkingSetSize";

        private const string QUERY_MEMORY1 = "SELECT * FROM Win32_PhysicalMemory";
        private const string QUERY_MEMORY2 = "SELECT * FROM Win32_PerfRawData_PerfOS_Memory";
        private const string QUERY_MEMORY3 = "SELECT * FROM Win32_Process";

        ILog logger = LogManager.GetLogger(typeof(MemoryMonitorCommand));

        [Parameter(Name = "appNames")]
        public string AppNames;

        [Execute]
        public void Run()
        {
            var query1 = new SelectQuery(QUERY_MEMORY1);
            var query2 = new SelectQuery(QUERY_MEMORY2);
            var query3 = new SelectQuery(QUERY_MEMORY3);
            var searcher1 = new ManagementObjectSearcher(query1);
            var searcher2 = new ManagementObjectSearcher(query2);
            var searcher3 = new ManagementObjectSearcher(query3);

            var capacity = 0.0;
            var free = 0.0;
            foreach (var o in searcher1.Get())
                capacity += (double)Convert.ToUInt64(o[PROPERTY_CAPACITY]) / (double)(1024 * 1024);
            foreach (var o in searcher2.Get())
                free += (double)Convert.ToUInt64(o[PROPERTY_AVAILABLE_BYTES]) / (double)(1024 * 1024);
            //var appsUsed = new Dictionary<string, double>();
            //var apps = AppNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            //foreach (var app in apps)
            //{
            //    var appUsed = 0.0;
            //    foreach (var o in searcher3.Get())
            //        if (string.Equals(Convert.ToString(o[PROPERTY_PROCESS_NAME]), app, StringComparison.OrdinalIgnoreCase))
            //            appUsed += (double)Convert.ToUInt64(o[PROPERTY_WORKING_SET_SIZE]) / (double)(1024 * 1024);
            //    appsUsed.Add(app, appUsed);
            //}
            var appsUsed = new Dictionary<string, Dictionary<uint, double>>();
            var apps = AppNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var o in searcher3.Get())
            {
                var appName = Convert.ToString(o[PROPERTY_PROCESS_NAME]);
                foreach (var app in apps)
                {
                    if (string.Equals(appName, app, StringComparison.OrdinalIgnoreCase))
                    {
                        var appId = Convert.ToUInt32(o[PROPERTY_PROCESS_ID]);
                        var workingSetSize = (double)Convert.ToUInt64(o[PROPERTY_WORKING_SET_SIZE]) / (double)(1024 * 1024);
                        if (appsUsed.ContainsKey(appName))
                            appsUsed[appName].Add(appId, workingSetSize);
                        else
                            appsUsed.Add(appName, new Dictionary<uint, double>() 
                        {
                            { 
                                appId, workingSetSize 
                            } 
                        });
                        break;
                    }
                }
            }

            var memInfo = new MemoryInfo()
            {
                Capacity = capacity,
                Free = free,
                Used = capacity - free,
                AppsUsed = appsUsed
            };

            var bin = new BinaryFormatter();
            var ms = new MemoryStream();
            bin.Serialize(ms, memInfo);
            logger.Info("memory monitor begin execute callback");
            CommandContext.Instance.SendMessage("memory usage info", ms.ToArray());
            logger.Info("memory monitor end execute callback");
        }

    }
}

 

posted @ 2014-01-14 17:46  doo  阅读(1877)  评论(0编辑  收藏  举报