隐藏

C# 监测指定进程的CPU占用率

发布:2022/12/2 19:28:47作者:管理员 来源:本站 浏览次数:801

     /// <summary>

     /// 监测性能

     /// </summary>

     /// <returns></returns>

     private bool MonitorPerformance()

     {

         bool res = false;

         int times = 1;

         int interval = 1000;//Sleep的时间间隔

         TimeSpan prevCpuTime = TimeSpan.Zero; //上次记录CPU的时间

         try

         {

             while (true)

             {

                 Process[] pros = Process.GetProcessesByName(ProcessName);

                 if (pros.Length > 0)

                 {

                     foreach (Process item in pros)

                     {

                         PerformanceCounter curpc = new PerformanceCounter("Process", "Working Set", item.ProcessName);

                         //当前时间

                         TimeSpan curCpuTime = item.TotalProcessorTime;

                         //计算

                         double value = (curCpuTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;

                         prevCpuTime = curCpuTime;

                         //这个工作集是动态更新的

                         Console.WriteLine("{0}:{1}  {2:N}KB CPU使用率:{3}", item.ProcessName, "工作集", curpc.NextValue() / 1024, value);

                         if (value < 5)

                         {

                             res = true;

                             item.Kill();

                         }

                         Thread.Sleep(interval);

                     }

                 }

                 else

                 {

                     break;

                 }

                 if (times * interval == 900000)//十五分钟后超时

                 {

                     foreach (Process item in pros)

                     {

                         KillProcessAndChildren(item.Id);

                     }

                     break;

                 }

                 times++;

             }

         }

         catch (Exception ex)

         {

             Console.WriteLine("Function: MonitorPerformance " + ex.Message);

         }

         return res;

     }