17 using System.Threading;
30 private CancellationTokenSource _cancellationTokenSource;
31 private Thread _connectionMonitorThread;
33 private bool _isEnabled;
34 private readonly
object _lockerConnectionMonitor =
new object();
35 private volatile bool _connectionLost;
36 private DateTime _lastDataReceivedTime;
86 using var waitHandle =
new ManualResetEvent(
false);
88 _cancellationTokenSource =
new CancellationTokenSource();
90 _connectionMonitorThread =
new Thread(() =>
94 var nextReconnectionAttemptUtcTime = DateTime.UtcNow;
97 lock (_lockerConnectionMonitor)
99 _lastDataReceivedTime = DateTime.UtcNow;
104 while (!_cancellationTokenSource.IsCancellationRequested
107 if (!_isEnabled)
continue;
112 lock (_lockerConnectionMonitor)
114 elapsed = DateTime.UtcNow - _lastDataReceivedTime;
119 _connectionLost =
true;
120 nextReconnectionAttemptUtcTime = DateTime.UtcNow.AddSeconds(nextReconnectionAttemptSeconds);
124 else if (_connectionLost)
128 _connectionLost =
false;
135 if (DateTime.UtcNow > nextReconnectionAttemptUtcTime)
139 nextReconnectionAttemptUtcTime = DateTime.UtcNow.AddSeconds(nextReconnectionAttemptSeconds);
146 catch (Exception exception)
148 Log.
Error($
"Error in DefaultConnectionHandler: {exception}");
152 catch (Exception exception)
156 }) { IsBackground =
true };
158 _connectionMonitorThread.Start();
160 waitHandle.WaitOne();
170 if (!_isEnabled && isEnabled)
175 _isEnabled = isEnabled;
184 lock (_lockerConnectionMonitor)
186 _lastDataReceivedTime = lastDataReceivedTime;
195 Log.
Error(
"DefaultConnectionHandler.OnConnectionLost(): WebSocket connection lost.");
204 Log.
Trace(
"DefaultConnectionHandler.OnConnectionRestored(): WebSocket connection restored.");
224 _connectionMonitorThread.StopSafely(TimeSpan.FromSeconds(5), _cancellationTokenSource);
225 _cancellationTokenSource?.DisposeSafely();