How can I get CPU load per core in C#?

前端 未结 3 1867
谎友^
谎友^ 2020-12-02 00:46

How can I get CPU Load per core (quadcore cpu), in C#?

Thanks :)

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 00:58

    First you need as many performance counters as cores (it takes time, you might want to do this in an async task, or it blocks you UI):

    CoreCount= Environment.ProcessorCount;
    CPUCounters = new PerformanceCounter[CoreCount];
    for (var i = 0; i < CoreCount; i++)
        CPUCounters[i] = new PerformanceCounter("Processor", "% Processor Time", $"{i}");
    

    Then you can fetch the value of usage of each core:

    public float[] CoreUsage { get; set; } // feel free to implement inpc
    
    public void Update() => CoreUsage = CPUCounters.Select(o => o.NextValue()).ToArray();
    

    However you might want to call Update() three times: the first time you'll always get 0.0, then second time always 0.0 or 100.0, and then at last the actual value.

    NextValue() gives you the instant value, not the mean value over time; if you want the mean value say over 1 second, you can use RawValue and calculate the mean as explained here: PerformanceCounter.RawValue Property

提交回复
热议问题