ConnectionCheckerV2.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using Vinno.IUS.Common.Log;
  5. using Vinno.vCloud.Common.FIS.Helper;
  6. using WingInterfaceLibrary.DTO.ServerInfo;
  7. using WingInterfaceLibrary.Interface;
  8. namespace Vinno.vCloud.Common.FIS
  9. {
  10. internal class ConnectionCheckerV2
  11. {
  12. private readonly IVinnoServerService _vinnoServerService;
  13. private readonly ManualResetEvent _waitEvent = new ManualResetEvent(false);
  14. private bool _defaultStatus;
  15. /// <summary>
  16. ///get or set connection check cycle
  17. /// </summary>
  18. internal int ConnectionCheckCycle { get; set; }
  19. public event EventHandler Offlined;
  20. public ConnectionCheckerV2(IVinnoServerService vinnoServerService, int connectionCheckCycle)
  21. {
  22. _vinnoServerService = vinnoServerService;
  23. ConnectionCheckCycle = connectionCheckCycle;
  24. }
  25. /// <summary>
  26. /// Start the Heartrate to keep the session available.
  27. /// </summary>
  28. public void Start(bool defaultStatus)
  29. {
  30. _defaultStatus = defaultStatus;
  31. Task.Run(() =>
  32. {
  33. while (!_waitEvent.WaitOne(TimeSpan.FromSeconds(ConnectionCheckCycle)))
  34. {
  35. DoCheck();
  36. }
  37. });
  38. }
  39. /// <summary>
  40. /// Stop the Heartrate
  41. /// </summary>
  42. public void Stop()
  43. {
  44. _waitEvent.Set();
  45. }
  46. private void DoCheck()
  47. {
  48. try
  49. {
  50. if (_defaultStatus)
  51. {
  52. if (!Check())
  53. {
  54. OnOfflined();
  55. }
  56. }
  57. else
  58. {
  59. OnOfflined();
  60. }
  61. }
  62. catch (Exception ex)
  63. {
  64. Logger.WriteLineError($"ConnectionCheckerV2 do check failed:{ex}");
  65. }
  66. }
  67. public bool Check()
  68. {
  69. try
  70. {
  71. EchoResult result = JsonRpcHelper.Echo(_vinnoServerService);
  72. if (result == null || result.Code != 0)
  73. {
  74. return false;
  75. }
  76. else
  77. {
  78. return true;
  79. }
  80. }
  81. catch (Exception ex)
  82. {
  83. Logger.WriteLineError($"ConnectionCheckerV2 check error:{ex}");
  84. return false;
  85. }
  86. }
  87. private void OnOfflined()
  88. {
  89. Offlined?.Invoke(this, EventArgs.Empty);
  90. }
  91. }
  92. }