AppInfoTool.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using Azylee.Core.ProcessUtils;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Text;
  7. namespace Azylee.Core.AppUtils
  8. {
  9. public class AppInfoTool
  10. {
  11. /// <summary>
  12. /// 读取APP Processor(可读取App的CPU使用率)
  13. /// </summary>
  14. /// <returns></returns>
  15. public static PerformanceCounter Processor()
  16. {
  17. Process p = null;
  18. PerformanceCounter processor = null;
  19. try
  20. {
  21. p = Process.GetCurrentProcess();
  22. processor = new PerformanceCounter("Process", "% Processor Time", p.ProcessName);
  23. }
  24. catch { }
  25. return processor;
  26. }
  27. /// <summary>
  28. /// 读取进程CPU使用率(同名进程无法支持)
  29. /// </summary>
  30. /// <param name="p"></param>
  31. /// <returns></returns>
  32. [Obsolete]
  33. public static PerformanceCounter Processor(Process p)
  34. {
  35. PerformanceCounter processor = null;
  36. try
  37. {
  38. string name = ProcessTool.GetInstanceNameById(p.Id);
  39. if (!string.IsNullOrWhiteSpace(name))
  40. {
  41. processor = new PerformanceCounter("Process", "% Processor Time", name);
  42. }
  43. }
  44. catch { }
  45. return processor;
  46. }
  47. /// <summary>
  48. /// 计算CPU占用率
  49. /// </summary>
  50. /// <param name="process"></param>
  51. /// <param name="begin"></param>
  52. /// <param name="end"></param>
  53. /// <param name="interval"></param>
  54. /// <returns></returns>
  55. public static double CalcCpuRate(Process process, TimeSpan begin, int interval)
  56. {
  57. //当前时间
  58. var current = process.TotalProcessorTime;
  59. //间隔时间内的CPU运行时间除以逻辑CPU数量
  60. double value = (current - begin).TotalMilliseconds / interval / Environment.ProcessorCount * 100;
  61. if (value < 0 || 100 < value) return 0;
  62. return value;
  63. }
  64. /// <summary>
  65. /// 读取APP占用内存(单位:KB)
  66. /// </summary>
  67. /// <returns></returns>
  68. public static long RAM()
  69. {
  70. long value = 0;
  71. Process p = null;
  72. try
  73. {
  74. p = Process.GetCurrentProcess();
  75. value = p.WorkingSet64 / 1024;
  76. }
  77. catch { }
  78. finally { p?.Dispose(); }
  79. return value;
  80. }
  81. public static long RAM(int id)
  82. {
  83. long value = 0;
  84. Process p = null;
  85. try
  86. {
  87. p = Process.GetProcessById(id);
  88. value = p.WorkingSet64 / 1024;
  89. }
  90. catch { }
  91. finally { p?.Dispose(); }
  92. return value;
  93. }
  94. public static long RAM(Process p)
  95. {
  96. long value = 0;
  97. try
  98. {
  99. value = p.WorkingSet64 / 1024;
  100. }
  101. catch { }
  102. finally { p?.Dispose(); }
  103. return value;
  104. }
  105. }
  106. }