1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- using System;
- using System.Threading;
- using System.Threading.Tasks;
- using Vinno.IUS.Common.Log;
- using Vinno.IUS.Common.Network.Leaf;
- namespace Vinno.vCloud.Common.FIS
- {
- internal class ConnectionChecker
- {
- private readonly ClientLeaf _leaf;
- private readonly ManualResetEvent _waitEvent = new ManualResetEvent(false);
- /// <summary>
- ///get or set connection check cycle
- /// </summary>
- private readonly int _connectionCheckCycle;
- public event EventHandler Offlined;
- public ConnectionChecker(ClientLeaf clientLeaf, int connectionCheckCycle)
- {
- _leaf = clientLeaf;
- _connectionCheckCycle = connectionCheckCycle;
- }
- /// <summary>
- /// Start the Heartrate to keep the session available.
- /// </summary>
- public void Start()
- {
- Task.Run(() =>
- {
- while (!_waitEvent.WaitOne(TimeSpan.FromSeconds(_connectionCheckCycle)))
- {
- DoCheck();
- }
- });
- }
- /// <summary>
- /// Stop the Heartrate
- /// </summary>
- public void Stop()
- {
- _waitEvent.Set();
- }
- private void DoCheck()
- {
- try
- {
- var echoResult = _leaf.Echo();
- if (!echoResult)
- {
- OnOfflined();
- }
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"Connection Checker do check failed:{ex}");
- }
- }
- private void OnOfflined()
- {
- Offlined?.Invoke(this, EventArgs.Empty);
- }
- }
- }
|