TimerViewModelBase.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows.Threading;
  6. using System.ComponentModel;
  7. using System.Threading.Tasks;
  8. using System.Reflection;
  9. using Aitex.Core.Util;
  10. using System.Windows;
  11. using Aitex.Core.RT.Log;
  12. namespace Aitex.Core.UI.MVVM
  13. {
  14. public abstract class TimerViewModelBase : ViewModelBase, ITimerViewModelBase
  15. {
  16. PeriodicJob _timer;
  17. static List<TimerViewModelBase> _lstAll = new List<TimerViewModelBase>();
  18. public static void StopAll()
  19. {
  20. foreach (TimerViewModelBase vm in _lstAll)
  21. vm.Stop();
  22. }
  23. public TimerViewModelBase(string name)
  24. {
  25. _timer = new PeriodicJob(1000, this.OnTimer, "UIUpdaterThread - " + name, false, true);
  26. _lstAll.Add(this);
  27. }
  28. //
  29. protected virtual bool OnTimer()
  30. {
  31. try
  32. {
  33. Poll();
  34. }
  35. catch (Exception ex)
  36. {
  37. LOG.Error(ex.Message);
  38. }
  39. return true;
  40. }
  41. public void Start()
  42. {
  43. _timer.Start();
  44. }
  45. public void Stop()
  46. {
  47. _timer.Stop();
  48. }
  49. public void Dispose()
  50. {
  51. Stop();
  52. }
  53. protected abstract void Poll();
  54. public virtual void UpdateData() { }
  55. public virtual void EnableTimer(bool enable)
  56. {
  57. if (enable) _timer.Start();
  58. else _timer.Pause();
  59. }
  60. }
  61. public interface ITimerViewModelBase
  62. {
  63. void EnableTimer(bool enable);
  64. }
  65. }