ConnectionChecker.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using Vinno.IUS.Common.Log;
  5. using Vinno.IUS.Common.Network.Leaf;
  6. namespace Vinno.vCloud.Common.FIS
  7. {
  8. internal class ConnectionChecker
  9. {
  10. private readonly ClientLeaf _leaf;
  11. private readonly ManualResetEvent _waitEvent = new ManualResetEvent(false);
  12. /// <summary>
  13. ///get or set connection check cycle
  14. /// </summary>
  15. private readonly int _connectionCheckCycle;
  16. public event EventHandler Offlined;
  17. public ConnectionChecker(ClientLeaf clientLeaf, int connectionCheckCycle)
  18. {
  19. _leaf = clientLeaf;
  20. _connectionCheckCycle = connectionCheckCycle;
  21. }
  22. /// <summary>
  23. /// Start the Heartrate to keep the session available.
  24. /// </summary>
  25. public void Start()
  26. {
  27. Task.Run(() =>
  28. {
  29. while (!_waitEvent.WaitOne(TimeSpan.FromSeconds(_connectionCheckCycle)))
  30. {
  31. DoCheck();
  32. }
  33. });
  34. }
  35. /// <summary>
  36. /// Stop the Heartrate
  37. /// </summary>
  38. public void Stop()
  39. {
  40. _waitEvent.Set();
  41. }
  42. private void DoCheck()
  43. {
  44. try
  45. {
  46. var echoResult = _leaf.Echo();
  47. if (!echoResult)
  48. {
  49. OnOfflined();
  50. }
  51. }
  52. catch (Exception ex)
  53. {
  54. Logger.WriteLineError($"Connection Checker do check failed:{ex}");
  55. }
  56. }
  57. private void OnOfflined()
  58. {
  59. Offlined?.Invoke(this, EventArgs.Empty);
  60. }
  61. }
  62. }