C#獲取計算機物理內存和可用內存大小封裝類SystemInfo

C#獲取計算機物理內存和可用內存大小封裝類SystemInfo

背景

在程序開發中經常會根據物理內存和可用內存大小的不用而執行不同的邏輯,尤其是在執行大數據量處理時,如果不做可用內存預判很容易出現內存溢出的情況,本文就分享一下在C#中如何獲取計算機物理內存大小和可用內存大小的方法。

代碼實現

SystemInfo.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Management;
using System.Runtime.InteropServices;

namespace Wongoing.Basic
{ 
    ///  
    /// 系統信息類 - 獲取CPU、內存、磁盤、進程信息 
    ///  
    public class SystemInfo
    {
        #region 字段定義

        private int m_ProcessorCount = 0;   //CPU個數 
        private PerformanceCounter pcCpuLoad;   //CPU計數器 
        private long m_PhysicalMemory = 0;   //物理內存 

        private const int GW_HWNDFIRST = 0;
        private const int GW_HWNDNEXT = 2;
        private const int GWL_STYLE = (-16);
        private const int WS_VISIBLE = 268435456;
        private const int WS_BORDER = 8388608;

        #endregion

        #region AIP聲明

        [DllImport("IpHlpApi.dll")]
        extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);

        [DllImport("User32")]
        private extern static int GetWindow(int hWnd, int wCmd);

        [DllImport("User32")]
        private extern static int GetWindowLongA(int hWnd, int wIndx);

        [DllImport("user32.dll")]
        private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);

        [DllImport("user32", CharSet = CharSet.Auto)]
        private extern static int GetWindowTextLength(IntPtr hWnd);

        #endregion

        #region 單例實現

        private static SystemInfo _instance = null;

        #region 構造函數
        ///  
        /// 構造函數,初始化計數器等 
        ///  
        private SystemInfo()
        {
            ////初始化CPU計數器 
            //pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            //pcCpuLoad.MachineName = ".";
            //pcCpuLoad.NextValue();

            ////CPU個數 
            //m_ProcessorCount = Environment.ProcessorCount; 

            //獲得物理內存 
            ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (mo["TotalPhysicalMemory"] != null)
                {
                    m_PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());
                }
            }
        }
        #endregion

        /// <summary>
        /// 靜態實例
        /// </summary>
        public static SystemInfo Instance
        {
            get
            {
                lock ("SystemInfo")
                {
                    if (_instance == null)
                    {
                        _instance = new SystemInfo();
                    }
                    return _instance;
                }
            }
        }

        #endregion

        #region CPU個數

        ///  
        /// 獲取CPU個數 
        ///  
        public int ProcessorCount
        {
            get
            {
                return m_ProcessorCount;
            }
        }

        #endregion

        #region CPU佔用率

        ///  
        /// 獲取CPU佔用率 
        ///  
        public float CpuLoad
        {
            get
            {
                return pcCpuLoad.NextValue();
            }
        }

        #endregion

        #region 可用內存

        ///  
        /// 獲取可用內存 
        ///  
        public long MemoryAvailable
        {
            get
            {
                long availablebytes = 0;
                //ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_PerfRawData_PerfOS_Memory"); 
                //foreach (ManagementObject mo in mos.Get()) 
                //{ 
                //    availablebytes = long.Parse(mo["Availablebytes"].ToString()); 
                //} 
                ManagementClass mos = new ManagementClass("Win32_OperatingSystem");
                foreach (ManagementObject mo in mos.GetInstances())
                {
                    if (mo["FreePhysicalMemory"] != null)
                    {
                        availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());
                    }
                }
                return availablebytes;
            }
        }

        #endregion

        #region 物理內存

        ///  
        /// 獲取物理內存 
        ///  
        public long PhysicalMemory
        {
            get
            {
                return m_PhysicalMemory;
            }
        }

        #endregion 
    } 
}

調用代碼

double available = SystemInfo.Instance.MemoryAvailable / 1024.0 / 1024.0 / 1014.0;                          //可用內存
double used = (SystemInfo.Instance.PhysicalMemory - SystemInfo.Instance.MemoryAvailable) / 1024.0 / 1024.0 / 1024.0;    //已用內存
double physicalMemory = SystemInfo.Instance.PhysicalMemory / 1024.0 / 1024.0 / 1024.0;                      //物理內存總量
Console.WriteLine("可用內存:" + String.Format("{0:f2}GB", available));
Console.WriteLine("物理內存:" + String.Format("{0:f2}GB", physicalMemory));
Console.WriteLine("內存用比:" + String.Format("{0:f2}/{1:f2}GB({2:f0}%)", used, physicalMemory, (SystemInfo.Instance.PhysicalMemory - SystemInfo.Instance.MemoryAvailable) * 100.0 / SystemInfo.Instance.PhysicalMemory));

運行結果

運行結果如下圖:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章