我一直試圖實作一個CPU監控器,每兩秒更新一次,并在WinForms中顯示在一個名為 "cpu_usage "的標簽上。不幸的是,我的代碼似乎不作業,并在運行時產生了這個錯誤:
System.InvalidOperationException: '跨執行緒操作無效。控制元件'cpu_usage'從它創建的執行緒以外的執行緒訪問。
到目前為止,我已經做了一點除錯,發現只要我試圖在 "cpu-usage "標簽上顯示百分比,就會發生錯誤,但我仍然無法弄清楚如何解決這個問題。CPU監控代碼如下:
public my_form()
{
InitializeComponent()。
//加載CPU監視器
cpuCounter = new PerformanceCounter()。
cpuCounter.CategoryName = "處理器"。
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
InitTimer()。
}
//CPU百分比檢查程式的定時器。
public void InitTimer()
{
cpu_timer = new Timer()。
cpu_timer.Elapsed = new ElapsedEventHandler(cpu_timer_Tick)。
cpu_timer.Interval = 2000;
cpu_timer.Start()。
}
//Initates the checking routine。
private void cpu_timer_Tick(objectsender, EventArgs e)。
{
cpu_usage.Text = getCurrentCpuUsage(); //這一行導致例外錯誤。
}
//尋找CPU資源的方法。
public string getCurrentCpuUsage()
{
string value1 = (int)cpuCounter.NextValue() "%"/span>;
Thread.Sleep(500)。
string value2 = (int)cpuCounter.NextValue() "%"/span>;
return value2.ToString()。
}
uj5u.com熱心網友回復:
我通過對計時器使用System.Windows.Forms,而不是使用System.Timer.Timer命名空間,成功地解決了這個錯誤。此外,我改變了我的代碼,使用 await 和 async,以確保運行用戶界面的執行緒在更新期間不會被凍結。新的代碼如下:
//CPU百分比檢查程式的計時器
public void InitTimer()
{
cpu_timer.Tick = new EventHandler(cpu_timer_Tick)。
cpu_timer.Interval = 2000; // in miliseconds。
cpu_timer.Start()。
}
//Initates the checking routine。
private async void cpu_timer_Tick(object sender, EventArgs e)。
{
Task<string> cpu_task = new Task<string> (getCurrentCpuUsage)。
cpu_task.Start();
cpu_usage.Text = await cpu_task;
}
uj5u.com熱心網友回復:
就像其他人說的,我相信你想在UI執行緒上執行文本的設定......可以試試這樣的方法:
//啟動檢查程式
private void cpu_timer_Tick(object sender, EventArgs e)。
{
cpu_usage.Invoke((MethodInvoker)delegate {
//在UI執行緒上運行。
cpu_usage.Text = getCurrentCpuUsage()。
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/309690.html
標籤:
