我嘗試設定一個非常簡單的應用程式。應用程式應顯示當前的 CPU 使用率。
我的觀點:
<Grid>
<Label Content="{Binding CpuUsage}" />
</Grid>
我的 MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
我的視圖模型:
public partial class ViewModel : ObservableObject
{
[ObservableProperty]
private string _cpuUsage;
public ViewModel()
{
SetTimerActions();
}
private void SetTimerActions()
{
var dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick = new EventHandler(SetCpuUsageVariable);
dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 1);
dispatcherTimer.Start();
}
private void SetCpuUsageVariable(object sender, EventArgs e)
{
var systemCpuUsage = Utils.GetCPUUsage();
CpuUsage = $"CPU: {systemCpuUsage}";
}
}
我的工具:
public static string GetCPUUsage()
{
PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
var CPUUsagePercentage = cpuCounter.NextValue() / Environment.ProcessorCount;
Trace.WriteLine($"CPU Usage: {string.Format("{0:N2}", CPUUsagePercentage)}");
return Convert.ToString(CPUUsagePercentage);
}
輸出始終為 0。原因是因為 .NextValue() 需要與“舊”值進行比較,但我每秒都會呼叫該方法。
有什么好的方法可以解決?
@邁克的回答:是的,這是可能的,但這些值仍然是錯誤的。
我將我的代碼更改為您建議的解決方案,但這些值是錯誤的/無意義的。
我啟動了 CPU 壓力,我的 CPU 負載是:~80%。
輸出是:
...
CPU Usage: 0,00
CPU Usage: 0,00
CPU Usage: 0,35
CPU Usage: 0,36
CPU Usage: 0,35
CPU Usage: 0,00
CPU Usage: 0,37
CPU Usage: 0,68
CPU Usage: 0,00
CPU Usage: 0,00
...
uj5u.com熱心網友回復:
我會cpuCounter
在您的實用程式中設定私有和靜態,以便在整個實用程式中僅創建一次新物件:
private static PerformanceCounter _cpuCounter = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
然后你GetCPUUsage
看起來像:
public static string GetCPUUsage()
{
var CPUUsagePercentage = _cpuCounter.NextValue() / Environment.ProcessorCount;
Trace.WriteLine($"CPU Usage: {string.Format("{0:N2}", CPUUsagePercentage)}");
return Convert.ToString(CPUUsagePercentage);
}
而且,一般來說,我會創建一個 float 或 double 并處理視圖模型GetCPUUsage
中的格式。SetCpuUsageVariable
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/537159.html