コード例 #1
0
        /// <summary>
        /// Returns the current memory information.  Framework objects are used where they exist.  The Windows API will
        /// where they do not exist.
        /// </summary>
        private static MemoryInfo WindowsMemoryInfo()
        {
            var mem = new MEMORYSTATUSEX();

            mem.Init();

            if (!GlobalMemoryStatusEx(ref mem))
            {
                throw new Win32Exception("Could not obtain memory information due to internal error.");
            }

            var mi = new MemoryInfo
            {
                ProcessUsed       = Process.GetCurrentProcess().WorkingSet64 / 1024,
                SystemTotal       = mem.ullTotalPhys,
                SystemFree        = mem.ullAvailPhys,
                SystemAvailable   = mem.ullAvailPhys,
                VirtualTotal      = mem.ullTotalVirtual,
                VirtualAvailable  = mem.ullAvailVirtual,
                PageFileTotal     = mem.ullTotalPageFile,
                PageFileAvailable = mem.ullAvailPageFile,
                MemoryLoad        = mem.dwMemoryLoad,
                ExtendedVirtualMemoryAvailable = mem.ullAvailExtendedVirtual
            };

            mi.SystemUsed = mi.SystemTotal - mi.SystemFree;

            return(mi);
        }
コード例 #2
0
ファイル: NativeMethods.cs プロジェクト: balchandra/ignite-1
        /// <summary>
        /// Gets the total physical memory.
        /// </summary>
        internal static ulong GetTotalPhysicalMemory()
        {
            var status = new MEMORYSTATUSEX();

            status.Init();

            GlobalMemoryStatusEx(ref status);

            return(status.ullTotalPhys);
        }
コード例 #3
0
        static MemoryInfo GetMemoryWindows()
        {
            MEMORYSTATUSEX ex = default;

            ex.Init();
            if (GlobalMemoryStatusEx(ref ex))
            {
                return(new MemoryInfo((long)ex.AvailPhys, (long)ex.TotalPhys));
            }
            return(null);
        }
コード例 #4
0
ファイル: BuildingIndex.cs プロジェクト: disooqi/searcho
 private bool isMemoryEmpty()
 {
     stat.Init();
     NativeMethods.GlobalMemoryStatusEx(ref stat);
     if (stat.ullAvailPhys > 55000000)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
コード例 #5
0
        public static bool GlobalMemoryStatusEx(out long ullAvailPhys, out long ullAvailVirtual)
        {
            MEMORYSTATUSEX mEMORYSTATUSEX = default(MEMORYSTATUSEX);

            mEMORYSTATUSEX.Init();
            if (NativeMethodsGeneral.GlobalMemoryStatusEx(ref mEMORYSTATUSEX) != 0)
            {
                ullAvailPhys    = mEMORYSTATUSEX.ullAvailPhys;
                ullAvailVirtual = mEMORYSTATUSEX.ullAvailVirtual;
                return(true);
            }
            ullAvailPhys    = 0L;
            ullAvailVirtual = 0L;
            return(false);
        }
コード例 #6
0
        public static bool GlobalMemoryStatusEx(out long ullAvailPhys, out long ullAvailVirtual)
        {
            MEMORYSTATUSEX memoryStatusEx = default(MEMORYSTATUSEX);

            memoryStatusEx.Init();
            if (GlobalMemoryStatusEx(ref memoryStatusEx) != 0)
            {
                ullAvailPhys    = memoryStatusEx.ullAvailPhys;
                ullAvailVirtual = memoryStatusEx.ullAvailVirtual;
                return(true);
            }
            ullAvailPhys    = 0L;
            ullAvailVirtual = 0L;
            return(false);
        }
コード例 #7
0
ファイル: Windows.cs プロジェクト: ME3Tweaks/ComputerInfo
 private void Refresh()
 {
     if (isOldOS)
     {
         memoryStatus = new MEMORYSTATUS();
         GlobalMemoryStatus(ref memoryStatus);
     }
     else
     {
         memoryStatusEx = new MEMORYSTATUSEX();
         memoryStatusEx.Init();
         if (!GlobalMemoryStatusEx(ref memoryStatusEx))
         {
             throw new Win32Exception("Could not obtain memory information due to internal error.");
         }
     }
 }
コード例 #8
0
    private void Refresh()
    {
        try
        {
            if (_monoTotalMemoryCounter != null && _monoAvailableMemoryCounter != null)
            {
                _totalPhysicalMemory     = (ulong)_monoTotalMemoryCounter.NextValue();
                _availablePhysicalMemory = (ulong)_monoAvailableMemoryCounter.NextValue();
            }
            else if (Environment.OSVersion.Version.Major < 5)
            {
                var memoryStatus = MEMORYSTATUS.Init();
                GlobalMemoryStatus(ref memoryStatus);

                if (memoryStatus.dwTotalPhys > 0)
                {
                    _availablePhysicalMemory = memoryStatus.dwAvailPhys;
                    _totalPhysicalMemory     = memoryStatus.dwTotalPhys;
                }
                else if (_netAvailableMemoryCounter != null)
                {
                    _availablePhysicalMemory = (ulong)_netAvailableMemoryCounter.NextValue();
                }
            }
            else
            {
                var memoryStatusEx = MEMORYSTATUSEX.Init();

                if (GlobalMemoryStatusEx(ref memoryStatusEx))
                {
                    _availablePhysicalMemory = memoryStatusEx.ullAvailPhys;
                    _totalPhysicalMemory     = memoryStatusEx.ullTotalPhys;
                }
                else if (_netAvailableMemoryCounter != null)
                {
                    _availablePhysicalMemory = (ulong)_netAvailableMemoryCounter.NextValue();
                }
            }
        }
        catch
        {
            // ignored
        }
    }
コード例 #9
0
        /// <summary>获取实时数据,如CPU、内存、温度</summary>
        public void Refresh()
        {
#if __CORE__
            if (Runtime.Windows)
            {
                //var str = "";

                //var cpu = ReadWmic("cpu", "Name", "ProcessorId", "LoadPercentage");
                //if (cpu != null)
                //{
                //    if (cpu.TryGetValue("Name", out str)) Processor = str;
                //    if (cpu.TryGetValue("ProcessorId", out str)) CpuID = str;
                //    if (cpu.TryGetValue("LoadPercentage", out str)) CpuRate = (Single)(str.ToDouble() / 100);
                //}

                MEMORYSTATUSEX ms = default;
                ms.Init();
                if (GlobalMemoryStatusEx(ref ms))
                {
                    Memory          = ms.ullTotalPhys;
                    AvailableMemory = ms.ullAvailPhys;
                }
            }
            // 特别识别Linux发行版
            else if (Runtime.Linux)
            {
                var str = "";

                var dic = ReadInfo("/proc/meminfo");
                if (dic != null)
                {
                    if (dic.TryGetValue("MemTotal", out str))
                    {
                        Memory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024;
                    }

                    if (dic.TryGetValue("MemAvailable", out str) ||
                        dic.TryGetValue("MemFree", out str))
                    {
                        AvailableMemory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024;
                    }
                }

                var file = "/sys/class/thermal/thermal_zone0/temp";
                if (File.Exists(file))
                {
                    Temperature = File.ReadAllText(file).Trim().ToDouble() / 1000;
                }
                else
                {
                    // A2温度获取,Ubuntu 16.04 LTS, Linux 3.4.39
                    file = "/sys/class/hwmon/hwmon0/device/temp_value";
                    if (File.Exists(file))
                    {
                        Temperature = File.ReadAllText(file).Trim().Substring(null, ":").ToDouble();
                    }
                }

                //var upt = Execute("uptime");
                //if (!upt.IsNullOrEmpty())
                //{
                //    str = upt.Substring("load average:");
                //    if (!str.IsNullOrEmpty()) CpuRate = (Single)str.Split(",")[0].ToDouble();
                //}

                file = "/proc/loadavg";
                if (File.Exists(file))
                {
                    CpuRate = (Single)File.ReadAllText(file).Substring(null, " ").ToDouble();
                }
            }
#else
            AvailableMemory = _cinfo.AvailablePhysicalMemory;

            //if (_cpuCounter != null)
            //    CpuRate = _cpuCounter.NextValue() / 100;
            //else
            //    CpuRate = (Single)GetInfo("Win32_PerfFormattedData_PerfOS_Processor where name='_Total'", "PercentProcessorTime").ToDouble() / 100;
#endif

            if (Runtime.Windows)
            {
                GetSystemTimes(out var idleTime, out var kernelTime, out var userTime);

                var current = new SystemTime
                {
                    IdleTime   = idleTime.ToLong(),
                    KernelTime = kernelTime.ToLong(),
                    UserTime   = userTime.ToLong(),
                };

                if (_systemTime != null)
                {
                    var idle   = current.IdleTime - _systemTime.IdleTime;
                    var kernel = current.KernelTime - _systemTime.KernelTime;
                    var user   = current.UserTime - _systemTime.UserTime;
                    var total  = kernel + user;

                    CpuRate = total == 0 ? 0 : (Single)((Double)(total - idle) / total);
                }

                _systemTime = current;
            }
        }
コード例 #10
0
        /// <summary>获取实时数据,如CPU、内存、温度</summary>
        public void Refresh()
        {
            if (Runtime.Windows)
            {
                MEMORYSTATUSEX ms = default;
                ms.Init();
                if (GlobalMemoryStatusEx(ref ms))
                {
                    Memory          = ms.ullTotalPhys;
                    AvailableMemory = ms.ullAvailPhys;
                }
            }
            // 特别识别Linux发行版
            else if (Runtime.Linux)
            {
                var dic = ReadInfo("/proc/meminfo");
                if (dic != null)
                {
                    if (dic.TryGetValue("MemTotal", out var str))
                    {
                        Memory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024;
                    }

                    if (dic.TryGetValue("MemAvailable", out str) ||
                        dic.TryGetValue("MemFree", out str))
                    {
                        AvailableMemory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024;
                    }
                }

                var file = "/sys/class/thermal/thermal_zone0/temp";
                if (File.Exists(file))
                {
                    Temperature = File.ReadAllText(file).Trim().ToDouble() / 1000;
                }
                else
                {
                    // A2温度获取,Ubuntu 16.04 LTS, Linux 3.4.39
                    file = "/sys/class/hwmon/hwmon0/device/temp_value";
                    if (File.Exists(file))
                    {
                        Temperature = File.ReadAllText(file).Trim().Substring(null, ":").ToDouble();
                    }
                }

                //var upt = Execute("uptime");
                //if (!upt.IsNullOrEmpty())
                //{
                //    str = upt.Substring("load average:");
                //    if (!str.IsNullOrEmpty()) CpuRate = (Single)str.Split(",")[0].ToDouble();
                //}

                //file = "/proc/loadavg";
                //if (File.Exists(file)) CpuRate = (Single)File.ReadAllText(file).Substring(null, " ").ToDouble() / Environment.ProcessorCount;

                file = "/proc/stat";
                if (File.Exists(file))
                {
                    // CPU指标:user,nice, system, idle, iowait, irq, softirq
                    // cpu  57057 0 14420 1554816 0 443 0 0 0 0

                    using var reader = new StreamReader(file);
                    var line = reader.ReadLine();
                    if (!line.IsNullOrEmpty() && line.StartsWith("cpu"))
                    {
                        var vs      = line.TrimStart("cpu").Trim().Split(" ");
                        var current = new SystemTime
                        {
                            IdleTime  = vs[3].ToLong(),
                            TotalTime = vs.Take(7).Select(e => e.ToLong()).Sum().ToLong(),
                        };

                        var idle  = current.IdleTime - (_systemTime?.IdleTime ?? 0);
                        var total = current.TotalTime - (_systemTime?.TotalTime ?? 0);
                        _systemTime = current;

                        CpuRate = total == 0 ? 0 : ((Single)(total - idle) / total);
                    }
                }
            }

            if (Runtime.Windows)
            {
                GetSystemTimes(out var idleTime, out var kernelTime, out var userTime);

                var current = new SystemTime
                {
                    IdleTime  = idleTime.ToLong(),
                    TotalTime = kernelTime.ToLong() + userTime.ToLong(),
                };

                var idle  = current.IdleTime - (_systemTime?.IdleTime ?? 0);
                var total = current.TotalTime - (_systemTime?.TotalTime ?? 0);
                _systemTime = current;

                CpuRate = total == 0 ? 0 : ((Single)(total - idle) / total);
            }
        }
コード例 #11
0
        /// <summary>获取实时数据,如CPU、内存、温度</summary>
        public void Refresh()
        {
            if (Runtime.Windows)
            {
                MEMORYSTATUSEX ms = default;
                ms.Init();
                if (GlobalMemoryStatusEx(ref ms))
                {
                    Memory          = ms.ullTotalPhys;
                    AvailableMemory = ms.ullAvailPhys;
                }
            }
            // 特别识别Linux发行版
            else if (Runtime.Linux)
            {
                var dic = ReadInfo("/proc/meminfo");
                if (dic != null)
                {
                    if (dic.TryGetValue("MemTotal", out var str))
                    {
                        Memory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024;
                    }

                    if (dic.TryGetValue("MemAvailable", out str) ||
                        dic.TryGetValue("MemFree", out str))
                    {
                        AvailableMemory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024;
                    }
                }

                // respberrypi + fedora
                if (TryRead("/sys/class/thermal/thermal_zone0/temp", out var value) ||
                    TryRead("/sys/class/hwmon/hwmon0/temp1_input", out value) ||
                    TryRead("/sys/class/hwmon/hwmon0/temp2_input", out value) ||
                    TryRead("/sys/class/hwmon/hwmon0/device/hwmon/hwmon0/temp2_input", out value) ||
                    TryRead("/sys/devices/virtual/thermal/thermal_zone0/temp", out value))
                {
                    Temperature = value.ToDouble() / 1000;
                }
                // A2温度获取,Ubuntu 16.04 LTS, Linux 3.4.39
                else if (TryRead("/sys/class/hwmon/hwmon0/device/temp_value", out value))
                {
                    Temperature = value.Substring(null, ":").ToDouble();
                }

                // 电池剩余
                if (TryRead("/sys/class/power_supply/BAT0/energy_now", out var energy_now) &&
                    TryRead("/sys/class/power_supply/BAT0/energy_full", out var energy_full))
                {
                    Battery = energy_now.ToDouble() / energy_full.ToDouble();
                }
                else if (TryRead("/sys/class/power_supply/battery/capacity", out var capacity))
                {
                    Battery = capacity.ToDouble() / 100.0;
                }

                //var upt = Execute("uptime");
                //if (!upt.IsNullOrEmpty())
                //{
                //    str = upt.Substring("load average:");
                //    if (!str.IsNullOrEmpty()) CpuRate = (Single)str.Split(",")[0].ToDouble();
                //}

                //file = "/proc/loadavg";
                //if (File.Exists(file)) CpuRate = (Single)File.ReadAllText(file).Substring(null, " ").ToDouble() / Environment.ProcessorCount;

                var file = "/proc/stat";
                if (File.Exists(file))
                {
                    // CPU指标:user,nice, system, idle, iowait, irq, softirq
                    // cpu  57057 0 14420 1554816 0 443 0 0 0 0

                    using var reader = new StreamReader(file);
                    var line = reader.ReadLine();
                    if (!line.IsNullOrEmpty() && line.StartsWith("cpu"))
                    {
                        var vs      = line.TrimStart("cpu").Trim().Split(" ");
                        var current = new SystemTime
                        {
                            IdleTime  = vs[3].ToLong(),
                            TotalTime = vs.Take(7).Select(e => e.ToLong()).Sum().ToLong(),
                        };

                        var idle  = current.IdleTime - (_systemTime?.IdleTime ?? 0);
                        var total = current.TotalTime - (_systemTime?.TotalTime ?? 0);
                        _systemTime = current;

                        CpuRate = total == 0 ? 0 : ((Single)(total - idle) / total);
                    }
                }
            }

            if (Runtime.Windows)
            {
                GetSystemTimes(out var idleTime, out var kernelTime, out var userTime);

                var current = new SystemTime
                {
                    IdleTime  = idleTime.ToLong(),
                    TotalTime = kernelTime.ToLong() + userTime.ToLong(),
                };

                var idle  = current.IdleTime - (_systemTime?.IdleTime ?? 0);
                var total = current.TotalTime - (_systemTime?.TotalTime ?? 0);
                _systemTime = current;

                CpuRate = total == 0 ? 0 : ((Single)(total - idle) / total);

#if __CORE__
                if (!_excludes.Contains(nameof(Temperature)))
                {
                    var temp = ReadWmic(@"/namespace:\\root\wmi path MSAcpi_ThermalZoneTemperature", "CurrentTemperature");
                    if (temp != null && temp.Count > 0)
                    {
                        if (temp.TryGetValue("CurrentTemperature", out var str))
                        {
                            Temperature = (str.SplitAsInt().Average() - 2732) / 10.0;
                        }
                    }
                    else
                    {
                        _excludes.Add(nameof(Temperature));
                    }
                }

                if (!_excludes.Contains(nameof(Battery)))
                {
                    var battery = ReadWmic("path win32_battery", "EstimatedChargeRemaining");
                    if (battery != null && battery.Count > 0)
                    {
                        if (battery.TryGetValue("EstimatedChargeRemaining", out var str))
                        {
                            Battery = str.SplitAsInt().Average() / 100.0;
                        }
                    }
                    else
                    {
                        _excludes.Add(nameof(Battery));
                    }
                }
#else
                if (!_excludes.Contains(nameof(Temperature)))
                {
                    // 读取主板温度,不太准。标准方案是ring0通过IOPort读取CPU温度,太难在基础类库实现
                    var str = GetInfo("Win32_TemperatureProbe", "CurrentReading");
                    if (!str.IsNullOrEmpty())
                    {
                        Temperature = str.SplitAsInt().Average();
                    }
                    else
                    {
                        str = GetInfo("MSAcpi_ThermalZoneTemperature", "CurrentTemperature", "root/wmi");
                        if (!str.IsNullOrEmpty())
                        {
                            Temperature = (str.SplitAsInt().Average() - 2732) / 10.0;
                        }
                    }

                    if (str.IsNullOrEmpty())
                    {
                        _excludes.Add(nameof(Temperature));
                    }
                }

                if (!_excludes.Contains(nameof(Battery)))
                {
                    // 电池剩余
                    var str = GetInfo("Win32_Battery", "EstimatedChargeRemaining");
                    if (!str.IsNullOrEmpty())
                    {
                        Battery = str.SplitAsInt().Average() / 100.0;
                    }
                    else
                    {
                        _excludes.Add(nameof(Battery));
                    }
                }
#endif
            }
        }
コード例 #12
0
        /// <summary>获取实时数据,如CPU、内存、温度</summary>
        private void GetRuntime()
        {
#if __CORE__
            if (Runtime.Windows)
            {
                var str = "";

                var cpu = ReadWmic("cpu", "Name", "ProcessorId", "LoadPercentage");
                if (cpu != null)
                {
                    if (cpu.TryGetValue("Name", out str))
                    {
                        Processor = str;
                    }
                    if (cpu.TryGetValue("ProcessorId", out str))
                    {
                        CpuID = str;
                    }
                    if (cpu.TryGetValue("LoadPercentage", out str))
                    {
                        CpuRate = (Single)(str.ToDouble() / 100);
                    }
                }

                MEMORYSTATUSEX ms = default;
                ms.Init();
                if (GlobalMemoryStatusEx(ref ms))
                {
                    Memory          = ms.ullTotalPhys;
                    AvailableMemory = ms.ullAvailPhys;
                }
            }
            // 特别识别Linux发行版
            else if (Runtime.Linux)
            {
                var str = "";

                var dic = ReadInfo("/proc/meminfo");
                if (dic != null)
                {
                    if (dic.TryGetValue("MemTotal", out str))
                    {
                        Memory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024;
                    }

                    if (dic.TryGetValue("MemAvailable", out str) ||
                        dic.TryGetValue("MemFree", out str))
                    {
                        AvailableMemory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024;
                    }
                }

                var file = "/sys/class/thermal/thermal_zone0/temp";
                if (File.Exists(file))
                {
                    Temperature = File.ReadAllText(file).Trim().ToDouble() / 1000;
                }

                var upt = Execute("uptime");
                if (!upt.IsNullOrEmpty())
                {
                    str = upt.Substring("load average:");
                    if (!str.IsNullOrEmpty())
                    {
                        CpuRate = (Single)str.Split(",")[0].ToDouble();
                    }
                }
            }
#else
            AvailableMemory = _cinfo.AvailablePhysicalMemory;
            CpuRate         = _cpuCounter == null ? 0 : (_cpuCounter.NextValue() / 100);
#endif
        }
コード例 #13
0
        /// <summary>获取实时数据,如CPU、内存、温度</summary>
        public void Refresh()
        {
            if (Runtime.Windows)
            {
                MEMORYSTATUSEX ms = default;
                ms.Init();
                if (GlobalMemoryStatusEx(ref ms))
                {
                    Memory          = ms.ullTotalPhys;
                    AvailableMemory = ms.ullAvailPhys;
                }
            }
            // 特别识别Linux发行版
            else if (Runtime.Linux)
            {
                var dic = ReadInfo("/proc/meminfo");
                if (dic != null)
                {
                    if (dic.TryGetValue("MemTotal", out var str))
                    {
                        Memory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024;
                    }

                    if (dic.TryGetValue("MemAvailable", out str) ||
                        dic.TryGetValue("MemFree", out str))
                    {
                        AvailableMemory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024;
                    }
                }

                var file = "/sys/class/thermal/thermal_zone0/temp";
                if (File.Exists(file))
                {
                    Temperature = File.ReadAllText(file).Trim().ToDouble() / 1000;
                }
                else
                {
                    // A2温度获取,Ubuntu 16.04 LTS, Linux 3.4.39
                    file = "/sys/class/hwmon/hwmon0/device/temp_value";
                    if (File.Exists(file))
                    {
                        Temperature = File.ReadAllText(file).Trim().Substring(null, ":").ToDouble();
                    }
                }

                //var upt = Execute("uptime");
                //if (!upt.IsNullOrEmpty())
                //{
                //    str = upt.Substring("load average:");
                //    if (!str.IsNullOrEmpty()) CpuRate = (Single)str.Split(",")[0].ToDouble();
                //}

                file = "/proc/loadavg";
                if (File.Exists(file))
                {
                    CpuRate = (Single)File.ReadAllText(file).Substring(null, " ").ToDouble() / Environment.ProcessorCount;
                }
            }

            if (Runtime.Windows)
            {
                GetSystemTimes(out var idleTime, out var kernelTime, out var userTime);

                var current = new SystemTime
                {
                    IdleTime   = idleTime.ToLong(),
                    KernelTime = kernelTime.ToLong(),
                    UserTime   = userTime.ToLong(),
                };

                if (_systemTime != null)
                {
                    var idle   = current.IdleTime - _systemTime.IdleTime;
                    var kernel = current.KernelTime - _systemTime.KernelTime;
                    var user   = current.UserTime - _systemTime.UserTime;
                    var total  = kernel + user;

                    CpuRate = total == 0 ? 0 : (Single)((Double)(total - idle) / total);
                }

                _systemTime = current;
            }
        }
コード例 #14
0
ファイル: MachineInfo.cs プロジェクト: jiangguang5201314/X
        /// <summary>刷新</summary>
        public void Init()
        {
#if __CORE__
            var osv = Environment.OSVersion;
            OSVersion = osv.Version + "";
            OSName    = (osv + "").TrimStart("Microsoft").TrimEnd(OSVersion).Trim();

            if (Runtime.Windows)
            {
                var str = "";

                var os = ReadWmic("os", "Caption", "Version");
                if (os != null)
                {
                    if (os.TryGetValue("Caption", out str))
                    {
                        OSName = str.TrimStart("Microsoft").Trim();
                    }
                    if (os.TryGetValue("Version", out str))
                    {
                        OSVersion = str;
                    }
                }

                var csproduct = ReadWmic("csproduct", "Name", "UUID");
                if (csproduct != null)
                {
                    if (csproduct.TryGetValue("Name", out str))
                    {
                        Product = str;
                    }
                    if (csproduct.TryGetValue("UUID", out str))
                    {
                        UUID = str;
                    }
                }

                var cpu = ReadWmic("cpu", "Name", "ProcessorId", "LoadPercentage");
                if (cpu != null)
                {
                    if (cpu.TryGetValue("Name", out str))
                    {
                        Processor = str;
                    }
                    if (cpu.TryGetValue("ProcessorId", out str))
                    {
                        CpuID = str;
                    }
                    if (cpu.TryGetValue("LoadPercentage", out str))
                    {
                        CpuRate = (Single)(str.ToDouble() / 100);
                    }
                }

                MEMORYSTATUSEX ms = default;
                ms.Init();
                if (GlobalMemoryStatusEx(ref ms))
                {
                    Memory          = ms.ullTotalPhys;
                    AvailableMemory = ms.ullAvailPhys;
                }
            }
            // 特别识别Linux发行版
            else if (Runtime.Linux)
            {
                var str = GetLinuxName();
                if (!str.IsNullOrEmpty())
                {
                    OSName = str;
                }

                // 树莓派优先 Model
                var dic = ReadInfo("/proc/cpuinfo");
                if (dic != null)
                {
                    if (dic.TryGetValue("Model", out str) ||
                        dic.TryGetValue("Hardware", out str) ||
                        dic.TryGetValue("cpu model", out str) ||
                        dic.TryGetValue("model name", out str))
                    {
                        Processor = str;
                    }

                    if (dic.TryGetValue("Serial", out str))
                    {
                        CpuID = str;
                    }
                }

                dic = ReadInfo("/proc/meminfo");
                if (dic != null)
                {
                    if (dic.TryGetValue("MemTotal", out str))
                    {
                        Memory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024;
                    }

                    if (dic.TryGetValue("MemAvailable", out str) ||
                        dic.TryGetValue("MemFree", out str))
                    {
                        AvailableMemory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024;
                    }
                }

                var mid = "/etc/machine-id";
                if (!File.Exists(mid))
                {
                    mid = "/var/lib/dbus/machine-id";
                }
                if (File.Exists(mid))
                {
                    Guid = File.ReadAllText(mid).Trim();
                }

                var file = "/sys/class/thermal/thermal_zone0/temp";
                if (File.Exists(file))
                {
                    Temperature = File.ReadAllText(file).Trim().ToDouble() / 1000;
                }

                var dmi = Execute("dmidecode")?.SplitAsDictionary(":", "\n");
                if (dmi != null)
                {
                    if (dmi.TryGetValue("ID", out str))
                    {
                        CpuID = str.Replace(" ", null);
                    }
                    if (dmi.TryGetValue("UUID", out str))
                    {
                        UUID = str;
                    }
                    if (dmi.TryGetValue("Product Name", out str))
                    {
                        Product = str;
                    }
                    //if (TryFind(dmi, new[] { "Serial Number" }, out str)) Guid = str;
                }

                var upt = Execute("uptime");
                if (!upt.IsNullOrEmpty())
                {
                    str = upt.Substring("load average:");
                    if (!str.IsNullOrEmpty())
                    {
                        CpuRate = (Single)str.Split(",")[0].ToDouble();
                    }
                }
            }
#else
            // 性能计数器的初始化非常耗时
            Task.Factory.StartNew(() =>
            {
                _cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total")
                {
                    MachineName = "."
                };
                _cpuCounter.NextValue();
            });

            var reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography");
            if (reg != null)
            {
                Guid = reg.GetValue("MachineGuid") + "";
            }
            if (Guid.IsNullOrEmpty())
            {
                reg = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
                if (reg != null)
                {
                    Guid = reg.GetValue("MachineGuid") + "";
                }
            }

            var ci = new ComputerInfo();
            OSName    = ci.OSFullName.TrimStart("Microsoft").Trim();
            OSVersion = ci.OSVersion;
            Memory    = ci.TotalPhysicalMemory;

            _cinfo = ci;

            Processor = GetInfo("Win32_Processor", "Name");
            CpuID     = GetInfo("Win32_Processor", "ProcessorId");
            UUID      = GetInfo("Win32_ComputerSystemProduct", "UUID");
            Product   = GetInfo("Win32_ComputerSystemProduct", "Name");

            // 读取主板温度,不太准。标准方案是ring0通过IOPort读取CPU温度,太难在基础类库实现
            var str = GetInfo("MSAcpi_ThermalZoneTemperature", "CurrentTemperature");
            if (!str.IsNullOrEmpty())
            {
                Temperature = (str.ToDouble() - 2732) / 10.0;
            }
#endif
        }
コード例 #15
0
ファイル: MachineInfo.cs プロジェクト: hvppy/X
        private void RefreshWindows()
        {
            MEMORYSTATUSEX ms = default;

            ms.Init();
            if (GlobalMemoryStatusEx(ref ms))
            {
                Memory          = ms.ullTotalPhys;
                AvailableMemory = ms.ullAvailPhys;
            }

            GetSystemTimes(out var idleTime, out var kernelTime, out var userTime);

            var current = new SystemTime
            {
                IdleTime  = idleTime.ToLong(),
                TotalTime = kernelTime.ToLong() + userTime.ToLong(),
            };

            var idle  = current.IdleTime - (_systemTime?.IdleTime ?? 0);
            var total = current.TotalTime - (_systemTime?.TotalTime ?? 0);

            _systemTime = current;

            CpuRate = total == 0 ? 0 : ((Single)(total - idle) / total);

#if NETCOREAPP
            //if (!_excludes.Contains(nameof(Temperature)))
            //{
            //    // 读取主板温度,不太准。标准方案是ring0通过IOPort读取CPU温度,太难在基础类库实现
            //    var str = GetInfo("Win32_TemperatureProbe", "CurrentReading");
            //    if (!str.IsNullOrEmpty())
            //    {
            //        Temperature = str.SplitAsInt().Average();
            //    }
            //    else
            //    {
            //        str = GetInfo("MSAcpi_ThermalZoneTemperature", "CurrentTemperature", "root/wmi");
            //        if (!str.IsNullOrEmpty())
            //            Temperature = (str.SplitAsInt().Average() - 2732) / 10.0;
            //        else
            //        {
            //            if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteLine("Temperature信息无法读取");
            //            _excludes.Add(nameof(Temperature));
            //            Temperature = 0;
            //        }
            //    }
            //}

            //if (!_excludes.Contains(nameof(Battery)))
            //{
            //    // 电池剩余
            //    var str = GetInfo("Win32_Battery", "EstimatedChargeRemaining");
            //    if (!str.IsNullOrEmpty())
            //        Battery = str.SplitAsInt().Average() / 100.0;
            //    else
            //    {
            //        if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteLine("Battery信息无法读取");
            //        _excludes.Add(nameof(Battery));
            //        Battery = 0;
            //    }
            //}
#endif
            if (!_excludes.Contains(nameof(Temperature)))
            {
                var temp = ReadWmic(@"/namespace:\\root\wmi path MSAcpi_ThermalZoneTemperature", "CurrentTemperature");
                if (temp != null && temp.Count > 0)
                {
                    if (temp.TryGetValue("CurrentTemperature", out var str))
                    {
                        Temperature = (str.SplitAsInt().Average() - 2732) / 10.0;
                    }
                }
                else
                {
                    if (XTrace.Log.Level <= LogLevel.Debug)
                    {
                        XTrace.WriteLine("Temperature信息无法读取");
                    }
                    _excludes.Add(nameof(Temperature));
                    Temperature = 0;
                }
            }

            if (!_excludes.Contains(nameof(Battery)))
            {
                var battery = ReadWmic("path win32_battery", "EstimatedChargeRemaining");
                if (battery != null && battery.Count > 0)
                {
                    if (battery.TryGetValue("EstimatedChargeRemaining", out var str))
                    {
                        Battery = str.SplitAsInt().Average() / 100.0;
                    }
                }
                else
                {
                    if (XTrace.Log.Level <= LogLevel.Debug)
                    {
                        XTrace.WriteLine("Battery信息无法读取");
                    }
                    _excludes.Add(nameof(Battery));
                    Battery = 0;
                }
            }
        }