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); /// ///get or set connection check cycle /// private readonly int _connectionCheckCycle; public event EventHandler Offlined; public ConnectionChecker(ClientLeaf clientLeaf, int connectionCheckCycle) { _leaf = clientLeaf; _connectionCheckCycle = connectionCheckCycle; } /// /// Start the Heartrate to keep the session available. /// public void Start() { Task.Run(() => { while (!_waitEvent.WaitOne(TimeSpan.FromSeconds(_connectionCheckCycle))) { DoCheck(); } }); } /// /// Stop the Heartrate /// 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); } } }