SystemMonitorClass.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace MvvmScaffoldFrame48.DLL.WindowsTools
  8. {
  9. public class SystemMonitorClass
  10. {
  11. private readonly PerformanceCounter _cpuCounter;
  12. private readonly PerformanceCounter _ramCounter;
  13. Stopwatch stopwatch = Stopwatch.StartNew();
  14. private float HisCPUCounter = 0;
  15. public SystemMonitorClass()
  16. {
  17. _cpuCounter = new PerformanceCounter(
  18. "Processor", "% Processor Time", "_Total");
  19. _ramCounter = new PerformanceCounter(
  20. "Memory", "Available MBytes");
  21. }
  22. /// <summary>
  23. /// 获取CPU使用率
  24. /// </summary>
  25. /// <returns></returns>
  26. public float GetCpuUsage()
  27. {
  28. stopwatch.Stop();
  29. if (stopwatch.ElapsedMilliseconds > 1000)
  30. {
  31. stopwatch.Restart();
  32. HisCPUCounter = _cpuCounter.NextValue();
  33. }
  34. else
  35. {
  36. stopwatch.Start();
  37. }
  38. return HisCPUCounter;
  39. }
  40. /// <summary>
  41. /// 获取可用内存
  42. /// </summary>
  43. /// <returns></returns>
  44. public float GetAvailableMemory()
  45. {
  46. return _ramCounter.NextValue();
  47. }
  48. }
  49. }