0

I'm trying to track the memory and CPU usage using PerformanceCounter , this code works perfectly on some Pcs but on some others it stops in this line

cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);

and i don't know if it will respond or not because it takes so much time , anyone has an explication for this please ?

here is my code :

    public string[] DiagnosticSystem()
    {
        string[] res = { string.Empty, string.Empty };
        try
        {
            PerformanceCounter cpuCounter;
            PerformanceCounter ramCounter;
            cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
            double cp = cpuCounter.NextValue();
            while (cp == 0)
            {
                Thread.Sleep(500);
                cp = cpuCounter.NextValue();
                res[0] = "Utilisation de CPU : " + Math.Round(cp, 2).ToString(CultureInfo.InvariantCulture) + "%";
            }
            ramCounter = new PerformanceCounter("Memory", "Available MBytes", true);
            res[1] = "Mémoire Disponible : " + Math.Round(ramCounter.NextValue() / 1024, 2) + "Mb";
            return res;
        }
        catch (Exception ex)
        {
            res[0] = ex.ToString();
            res[1] = ex.ToString();
            return res;
        }
    }
  • I used it on several PCs and never has any problem. However if you need to sample the resources periodically, I recomend to create the counter objects (`cpuCounter`, `ramCounter`) once, keep them as members and only call `NextValue()` periodically. – wohlstad Apr 18 '22 at 09:45
  • I have to ask: Are you *sure* that the code stops in that line? If yes, why are you sure? I ask because it looks like your code has a non-terminating loop as long as `cp` returns 0, and that seems like a much more likely reason. – Heinzi Apr 18 '22 at 10:25
  • yes i'm sure because while debugging it stops there , that's why i couldn't find any explication .. –  Apr 18 '22 at 11:01
  • https://stackoverflow.com/questions/4209366/what-would-make-performancecountercategory-exists-hang-indefinitely – Hans Passant Apr 18 '22 at 13:05
  • Could you fix this error by stopping the print spooler service? https://stackoverflow.com/a/4237622/16764901 – Jiale Xue - MSFT Apr 19 '22 at 06:49
  • https://stackoverflow.com/questions/4209366/what-would-make-performancecountercategory-exists-hang-indefinitely/4237622#4237622 I followed this solution and does the job for me –  Jul 12 '22 at 14:12
  • When people ask for clarification it's better to fix the question than delete it. If you have a `ReportRow` with eg a title, total and children, you can easily create a recursive method `public decimal ChildrenTotal()=>Total + Children.Sum(c=>c.ChildrenTotal())`. If you can't add a method to the object you can probably use an extension method. But do you have a class with `Children` ? We can't guess – Panagiotis Kanavos Jul 12 '22 at 15:13

0 Answers0