C# 为什么循环时间这么长这么慢?

C# 为什么循环时间这么长这么慢?,c#,.net,winforms,C#,.net,Winforms,我为测试创建了一个新类: 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.Mana

我为测试创建了一个新类:

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;
            }
        }
这样,它的工作速度非常慢,需要很长时间才能完成每个循环。 一般来说,我希望循环每个正在运行的进程并获得它的cpuusage

但是如果我像这样移除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循环很慢

删除这些睡眠调用,让循环在另一个线程中运行,避免减慢用户界面


另外,我不明白您为什么要迭代Process返回的进程。GetProcesses:您没有使用它们。

quantdev您能告诉我如何至少在使用进程的部分这样做吗?另外,我不明白为什么要迭代Process.GetProcesses返回的进程:您没有使用它们,我想迭代所有正在运行的进程以获得每个进程的cpu值。我该怎么做?quantdev我必须使用线程。sleep1000;在新类中,如果没有,则不会给出正确的cpu使用率值。