用C#实时获取CPU利用率

using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.Runtime.InteropServices;
using  System.Threading;
using  System.Diagnostics; 

namespace  ConsoleApplication2
{
    
public delegate bool CallBack(int hwnd, int lParam);

    
class EnumWindowsApp
    
{

        [DllImport(
"user32")]

        
public static extern int EnumWindows(CallBack x, int y);

        
private const string CategoryName = "Processor";
        
private const string CounterName = "% Processor Time";
        
private const string InstanceName = "_Total";
        
private static void Say(string txt)
        
{
            Console.WriteLine(txt);
        }


        
//  auxiliary  print  methods  
        private static void Say()
        
{
            Say(
"");
        }


        
static void Main(string[] args)
        
{
            
try
            
{
                
//CallBack myCallBack = new CallBack(EnumWindowsApp.Report);

                
//EnumWindows(myCallBack, 0);
                
//Console.Read();
                Say("$Id:  CpuLoadInfo.cs,v  1.2  2007/07/03  17:45:48  rz65  Exp  $");
                Say();

                Say(
"Attempt  to  create  a  PerformanceCounter  instance:");
                Say(
"Category  name  =  " + CategoryName);
                Say(
"Counter  name    =  " + CounterName);
                Say(
"Instance  name  =  " + InstanceName);
                PerformanceCounter pc 
= new PerformanceCounter(CategoryName, CounterName, InstanceName);
                Say(
"Performance  counter  was  created.");
                Say(
"Property  CounterType:  " + pc.CounterType);
                Say();

                Say(
"Property  CounterHelp:  " + pc.CounterHelp);
                Say();
                Say(
"Entering  measurement  loop.");

                
while (true)
                
{
                    Thread.Sleep(
1000);  //  wait  for  1  second
                    float cpuLoad = pc.NextValue();//.Nextvalue();
                    Say("CPU  load  =  " + cpuLoad + "  %.");
                }

            }

            
catch(InvalidOperationException er)

            
{
                Console.WriteLine(er);
                Console.Read();
            }

        }

        
public static bool Report(int hwnd, int lParam)
        
{

            Console.Write(
"Window handle is :");

            Console.WriteLine(hwnd);

            
return true;

        }
 

    }

}

 

你可能感兴趣的:(用C#实时获取CPU利用率)