AppInfoTool.cs 3.2 KB

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