[英]Why the loop is taking so long and so slow?
我為測試創建了一個新類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenHardwareMonitor.Hardware;
using System.Diagnostics;
using DannyGeneral;
using System.Windows.Forms;
using System.Threading;
using System.Management;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
namespace HardwareMonitoring
{
class CpuUsages
{
public static string processes;
public static string cputest()
{
PerformanceCounter cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
var unused = cpuCounter.NextValue(); // first call will always return 0
System.Threading.Thread.Sleep(1000); // wait a second, then try again
//Console.WriteLine("Cpu usage: " + cpuCounter.NextValue() + "%");
processes = "Cpu usage: " + cpuCounter.NextValue() + "%";
return processes;
}
}
}
然后在form1中,我添加了一個新的計時器,將其設置為1000ms,在運行程序時啟用它,並且在計時器滴答事件中執行了以下操作:
private void timer3_Tick(object sender, EventArgs e)
{
Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
CpuUsages.cputest();
cpuusage = CpuUsages.processes;
label26.Text = cpuusage;
}
}
這樣,花費很長時間才能使foreach循環工作。 總的來說,我想遍歷每個正在運行的進程,並得到它的幫助。
但是,如果我這樣刪除foreach循環:
private void timer3_Tick(object sender, EventArgs e)
{
Process[] processes = Process.GetProcesses();
CpuUsages.cputest();
cpuusage = CpuUsages.processes;
label26.Text = cpuusage;
}
然后它將很快運行,我將在label26中每秒看到一次cpuusage更新。 問題在於它將僅顯示正在處理的cpuusage。
我該怎么解決? 總的來說,我想為列表中的每個進程創建自動的標簽數量,並顯示每個進程的進程。 但是,當我使用foreach循環時,它是如此的緩慢並且花費了很長時間。
有什么辦法解決嗎?
這個:
foreach (Process process in processes)
{
CpuUsages.cputest();
cpuusage = CpuUsages.processes;
label26.Text = cpuusage;
}
將使您的程序休眠1秒*(計算機上正在運行的進程數)。 難怪foreach
循環很慢。
刪除這些Sleep
調用,並使您的循環在另一個線程中運行,避免減慢用戶界面的速度。
另外,我也看不出為什么要遍歷Process.GetProcesses()
返回的processes
:您沒有使用它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.