繁体   English   中英

为什么循环要花这么长时间又这么慢?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM