@@ -19,7 +19,7 @@ public class CoinApiWsClient : ICoinApiWsClient, IDisposable
1919 private const string UrlProduction = "wss://ws.coinapi.io/" ;
2020
2121 private readonly string _url = UrlProduction ;
22-
22+
2323 private readonly CancellationTokenSource _cts = new CancellationTokenSource ( ) ;
2424 private readonly QueueThread < MessageData > _queueThread = null ;
2525
@@ -39,7 +39,7 @@ public class CoinApiWsClient : ICoinApiWsClient, IDisposable
3939 public long UnprocessedMessagesQueueSize => _queueThread . QueueSize ;
4040 public event EventHandler < Exception > Error ;
4141 public AutoResetEvent ConnectedEvent { get ; } = new AutoResetEvent ( false ) ;
42- public bool IsConnected => _client ? . State == WebSocketState . Open ;
42+ public bool IsConnected => _client ? . State == WebSocketState . Open ;
4343 public DateTime ? ConnectedTime { get ; private set ; }
4444 public ulong TotalBytesReceived { get ; private set ; }
4545 public TimeSpan TotalWaitTime => _waitStopwatch . Elapsed ;
@@ -99,7 +99,7 @@ private void _queueThread_ItemDequeuedEvent(object sender, MessageData item)
9999 return ;
100100 }
101101
102- switch ( messageType )
102+ switch ( messageType )
103103 {
104104 case MessageType . book :
105105 HandleBookItem ( sender , item ) ;
@@ -259,7 +259,7 @@ private async Task Connect()
259259 using ( var connectionCts = CancellationTokenSource . CreateLinkedTokenSource ( _cts . Token ) )
260260 {
261261 await HandleConnection ( connectionCts ) ;
262-
262+
263263 ConnectedTime = null ;
264264 TotalBytesReceived = 0 ;
265265 _waitStopwatch . Reset ( ) ;
@@ -284,8 +284,8 @@ private async Task HeartbeatWatcher(ClientWebSocket client, CancellationTokenSou
284284 if ( Interlocked . Increment ( ref _hbLastAction ) >= _hbLastActionMaxCount )
285285 {
286286 connectionCts . Cancel ( ) ;
287- await client . CloseAsync ( WebSocketCloseStatus . NormalClosure ,
288- nameof ( HeartbeatWatcher ) ,
287+ await client . CloseAsync ( WebSocketCloseStatus . NormalClosure ,
288+ nameof ( HeartbeatWatcher ) ,
289289 CancellationToken . None ) ;
290290 continue ;
291291 }
@@ -338,9 +338,22 @@ private async Task HandleConnection(CancellationTokenSource connectionCts)
338338 _queueThread . Enqueue ( messageData ) ;
339339 }
340340 }
341- catch ( TaskCanceledException )
341+ catch ( TaskCanceledException )
342342 {
343- await _client . CloseAsync ( WebSocketCloseStatus . NormalClosure , "Normal" , CancellationToken . None ) ;
343+ try
344+ {
345+ if ( _client . State == WebSocketState . Open )
346+ {
347+ await _client . CloseAsync ( WebSocketCloseStatus . NormalClosure , "Normal" , CancellationToken . None ) ;
348+
349+ }
350+
351+ }
352+ catch ( Exception ex )
353+ {
354+
355+ OnError ( ex ) ;
356+ }
344357 }
345358 catch ( Exception ex )
346359 {
0 commit comments