0

I'm attempting to use OpenHardwareMonitor to get CPU temperatures in a Windows Service project, but it doesn't work correctly when running the code as a service.

When looking around how to read CPU temp in C# I stumbled onto this thread: How to get CPU temperature?

Win32_TemperatureProbe doesn't seem to work and MSAcpi_ThermalZoneTemperature always returned the same low value, so naturally I tried the OpenHardwareMonitor solution in the replies. It works when running as a Console application with the highestAvailable requestedExecutionLevel, but doesn't when running as a Windows service installed to use LocalSystem.

using OpenHardwareMonitor.Hardware;

namespace Monitoring_Service
{
    public class Computer
    {

        ...

        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) { }
        }

        internal float GetTemperature()
        {
            var temp = 0f;

            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)
                            temp =  computer.Hardware[i].Sensors[j].Value.GetValueOrDefault();
                    }
                }
            }
            computer.Close();

            return temp;
        }
    }
}

When I run this in a Console application as Admin computer.Hardware[i].Sensors has 19 items, 0-4 are load, 5-9 are temperature, 10-13 are clock and so on. Thus the if statement succeeds and the temp variable is set.

When I run the same code as a Windows service and debug the Sensors list only contains 5 items, 0-4 which are load. How can this be?

0 Answers0