专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

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

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/2/14 1:12:14       共计:3613 浏览

     /// <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;

     }


版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:C#获取CPU和内存使用率 | ·下一条:在mssql中如何使用存储过程破解sa密码?

Copyright © 广州京杭网络科技有限公司 2005-2024 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有