ConnectionChecker.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. public event EventHandler Offlined;
  13. /// <summary>
  14. ///get or set connection check cycle
  15. /// </summary>
  16. internal int ConnectionCheckCycle { get; set; }
  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. }