C# 如何获取CPU温度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1195112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get CPU temperature?
提问by yeyeyerman
I need to gather some system's information for the application I'm developing. The memory available and the CPU load are easy to get using C#. Unfortunately, the CPU temperature it's not that easy. I have tried using WMI but I couldn't get anything using
我需要为我正在开发的应用程序收集一些系统信息。可用内存和 CPU 负载很容易使用 C# 获得。不幸的是,CPU 温度并不是那么容易。我曾尝试使用 WMI,但我无法使用任何东西
Win32_TemperatureProbe
or
或者
MSAcpi_ThermalZoneTemperature
Has anybody already dealt with this issue? I'm wondering how monitoring programs, as SiSoftware Sandra, can get that information...
有没有人已经处理过这个问题?我想知道作为 SiSoftware Sandra 的监控程序如何获得这些信息......
Just in case anybody is interested, here is the code of the class:
以防万一有人感兴趣,这里是类的代码:
public class SystemInformation
{
private System.Diagnostics.PerformanceCounter m_memoryCounter;
private System.Diagnostics.PerformanceCounter m_CPUCounter;
public SystemInformation()
{
m_memoryCounter = new System.Diagnostics.PerformanceCounter();
m_memoryCounter.CategoryName = "Memory";
m_memoryCounter.CounterName = "Available MBytes";
m_CPUCounter = new System.Diagnostics.PerformanceCounter();
m_CPUCounter.CategoryName = "Processor";
m_CPUCounter.CounterName = "% Processor Time";
m_CPUCounter.InstanceName = "_Total";
}
public float GetAvailableMemory()
{
return m_memoryCounter.NextValue();
}
public float GetCPULoad()
{
return m_CPUCounter.NextValue();
}
public float GetCPUTemperature()
{
//...
return 0;
}
}
采纳答案by samoz
I'm pretty sure it's manufacturer dependent, since they will be accessed through an I/O port. If you have a specific board you're trying to work with, try looking through the manuals and/or contacting the manufacturer.
我很确定它取决于制造商,因为它们将通过 I/O 端口访问。如果您尝试使用特定的电路板,请尝试查看手册和/或联系制造商。
If you want to do this for a lot of different boards, I'd recommend contacting someone at something like SiSoftware or be prepared to read a LOT of motherboard manuals.
如果您想对许多不同的主板执行此操作,我建议您联系 SiSoftware 之类的人员或准备阅读大量主板手册。
As another note, not all boards have temperature monitors.
另请注意,并非所有电路板都有温度监视器。
You also might run into problems getting privileged access from the kernel.
您还可能会遇到从内核获得特权访问的问题。
回答by Jon Grant
回答by Lasse Rasch
I know this post is old, but just wanted to add a comment if somebody should be looking at this post and trying to find a solution for this problem.
我知道这篇文章很旧,但只是想添加评论,如果有人应该查看这篇文章并试图找到解决此问题的方法。
You can indeed read the CPU temperature very easily in C# by using a WMI approach.
通过使用 WMI 方法,您确实可以在 C# 中非常轻松地读取 CPU 温度。
To get a Celsius value, I have created a wrapper that converts the value returned by WMI and wraps it into an easy to use object.
为了获得摄氏度值,我创建了一个包装器,用于转换 WMI 返回的值并将其包装成一个易于使用的对象。
Please remember to add a reference to the System.Management.dll
in Visual Studio.
请记住System.Management.dll
在 Visual Studio 中添加对 的引用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
namespace RCoding.Common.Diagnostics.SystemInfo
{
public class Temperature
{
public double CurrentValue { get; set; }
public string InstanceName { get; set; }
public static List<Temperature> Temperatures
{
get
{
List<Temperature> result = new List<Temperature>();
ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"root\WMI", "SELECT * FROM MSAcpi_ThermalZoneTemperature");
foreach (ManagementObject obj in searcher.Get())
{
Double temp = Convert.ToDouble(obj["CurrentTemperature"].ToString());
temp = (temp - 2732) / 10.0;
result.Add(new Temperature { CurrentValue = temp, InstanceName = obj["InstanceName"].ToString() });
}
return result;
}
}
}
}
Update 25.06.2010:
2010 年 6 月 25 日更新:
(Just saw that a link was posted to the same kind of solution above... Anyway, I will leave this piece of code if somebody should want to use it :-) )
(刚刚看到上面发布了一个链接到同一种解决方案......无论如何,如果有人想使用它,我会留下这段代码:-))
回答by Jens
For others who may come by here, maybe take a look at : http://openhardwaremonitor.org/
对于可能会来这里的其他人,也许看看:http: //openhardwaremonitor.org/
Follow that link and at first you might think, "hey that's an Application, that is why it was removed, the question was how to do this from C# code, not to find an application that can tell me the temperature..." This is where it shows you are not willing to invest enough time in reading what "Open Hardware Monitor" also is.
按照那个链接,一开始你可能会想,“嘿,这是一个应用程序,这就是它被删除的原因,问题是如何从 C# 代码中做到这一点,而不是找到一个可以告诉我温度的应用程序......”它表明您不愿意投入足够的时间来阅读“开放硬件监视器”也是如此。
They also include a Data Interface, here is the description:
它们还包括一个数据接口,这里是描述:
Data InterfaceThe Open Hardware Monitor publishes all sensor data to WMI (Windows Management Instrumentation). This allows other applications to read and use the sensor information as well. A preliminary documentation of the interface can be found here(click).
数据接口Open Hardware Monitor 将所有传感器数据发布到 WMI(Windows Management Instrumentation)。这也允许其他应用程序读取和使用传感器信息。可以在此处找到该界面的初步文档(单击)。
When you download it, it contains the OpenHardwareMonitor.exe application, you're not looking for that one. It also contains the OpenHardwareMonitorLib.dll, you're looking for that one.
当您下载它时,它包含 OpenHardwareMonitor.exe 应用程序,您不是在寻找那个应用程序。它还包含 OpenHardwareMonitorLib.dll,您正在寻找那个。
It is mostly, if not 100%, just a wrapper around the WinRing0 API, which you could choose to wrap your self if you feel like it.
它主要是(如果不是 100%)只是围绕 WinRing0 API 的一个包装器,如果您愿意,您可以选择包装自己。
I have tried this out from a C# app myself, and it works. Although it is still in beta, it seemed rather stable. It is also open source so it could be a good starting point instead.
我自己从 C# 应用程序中尝试过这个,它有效。虽然它仍处于测试阶段,但它似乎相当稳定。它也是开源的,因此它可能是一个很好的起点。
At the end of the day I find it hard to believe that is not on topic of this question.
归根结底,我很难相信这不是这个问题的主题。
回答by Jet
It can be done in your code via WMI. I've found a tool from Microsoft that creates code for it.
它可以通过 WMI 在您的代码中完成。我找到了 Microsoft 的一个工具,可以为其创建代码。
The WMI Code Creator tool allows you to generate VBScript, C#, and VB .NET code that uses WMI to complete a management task such as querying for management data, executing a method from a WMI class, or receiving event notifications using WMI.
WMI 代码创建器工具允许您生成使用 WMI 来完成管理任务的 VBScript、C# 和 VB .NET 代码,例如查询管理数据、执行 WMI 类中的方法或使用 WMI 接收事件通知。
You can download it here.
你可以在这里下载。
回答by haoming weng
It's depends on if your computer support WMI
. My computer can't run this WMI demo too.
这取决于您的计算机是否支持WMI
。我的电脑也不能运行这个 WMI 演示。
But I successfully get the CPU temperature via Open Hardware Monitor. Add the Openhardwaremonitor reference in Visual Studio. It's easier. Try this
但是我通过 Open Hardware Monitor 成功获得了 CPU 温度。在 Visual Studio 中添加 Openhardwaremonitor 引用。这更容易。尝试这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenHardwareMonitor.Hardware;
namespace Get_CPU_Temp5
{
class Program
{
public class UpdateVisitor : IVisitor
{
public void VisitComputer(IComputer computer)
{
computer.Traverse(this);
}
public void VisitHardware(IHardware hardware)
{
hardware.Update();
foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
}
public void VisitSensor(ISensor sensor) { }
public void VisitParameter(IParameter parameter) { }
}
static void GetSystemInfo()
{
UpdateVisitor updateVisitor = new UpdateVisitor();
Computer computer = new Computer();
computer.Open();
computer.CPUEnabled = true;
computer.Accept(updateVisitor);
for (int i = 0; i < computer.Hardware.Length; i++)
{
if (computer.Hardware[i].HardwareType == HardwareType.CPU)
{
for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++)
{
if (computer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
Console.WriteLine(computer.Hardware[i].Sensors[j].Name + ":" + computer.Hardware[i].Sensors[j].Value.ToString() + "\r");
}
}
}
computer.Close();
}
static void Main(string[] args)
{
while (true)
{
GetSystemInfo();
}
}
}
}
You need to run this demo as administrator.
您需要以管理员身份运行此演示。
You can see the tutorial here: http://www.lattepanda.com/topic-f11t3004.html
你可以在这里看到教程:http: //www.lattepanda.com/topic-f11t3004.html
回答by TheQult
I extracted the CPU part from Open Hardware Monitor into a separated library, exposing sensors and members normally hidden into OHM. It also includes many updates (like the support for Ryzen and Xeon) because on OHM they don't accept pull requests since 2015.
我将 CPU 部分从 Open Hardware Monitor 提取到一个单独的库中,暴露了通常隐藏在 OHM 中的传感器和成员。它还包括许多更新(例如对 Ryzen 和 Xeon 的支持),因为在 OHM 上,他们自 2015 年以来不接受拉取请求。
https://www.nuget.org/packages/HardwareProviders.CPU.Standard/
https://www.nuget.org/packages/HardwareProviders.CPU.Standard/
Let know your opinion :)
让你知道你的意见:)
回答by Ali Zahid
You can give the Open Hardware Monitor a go, although it lacks support for the latest processors.
您可以试试 Open Hardware Monitor,尽管它缺乏对最新处理器的支持。
internal sealed class CpuTemperatureReader : IDisposable
{
private readonly Computer _computer;
public CpuTemperatureReader()
{
_computer = new Computer { CPUEnabled = true };
_computer.Open();
}
public IReadOnlyDictionary<string, float> GetTemperaturesInCelsius()
{
var coreAndTemperature = new Dictionary<string, float>();
foreach (var hardware in _computer.Hardware)
{
hardware.Update(); //use hardware.Name to get CPU model
foreach (var sensor in hardware.Sensors)
{
if (sensor.SensorType == SensorType.Temperature && sensor.Value.HasValue)
coreAndTemperature.Add(sensor.Name, sensor.Value.Value);
}
}
return coreAndTemperature;
}
public void Dispose()
{
try
{
_computer.Close();
}
catch (Exception)
{
//ignore closing errors
}
}
}
Download the zip from the official source, extract and add a reference to OpenHardwareMonitorLib.dll in your project.
从官方源下载 zip ,解压并在您的项目中添加对 OpenHardwareMonitorLib.dll 的引用。