Example #1
0
        private void StartMonitor()
        {
            _monitorTask = Task.Run(() =>
            {
                _monitorRunning    = true;
                var needsReconnect = false;
                try
                {
                    var lastState = State;
                    while (_ws != null && !_disposedValue)
                    {
                        if (lastState == State)
                        {
                            Thread.Sleep(200);
                            continue;
                        }

                        OnStateChanged?.Invoke(State, lastState);

                        if (State == WebSocketState.Open)
                        {
                            OnOpened?.Invoke();
                        }

                        if ((State == WebSocketState.Closed || State == WebSocketState.Aborted) && !_reconnecting)
                        {
                            if (lastState == WebSocketState.Open && !_disconnectCalled && _reconnectStrategy != null &&
                                !_reconnectStrategy.AreAttemptsComplete())
                            {
                                // go through the reconnect strategy
                                // Exit the loop and start async reconnect
                                needsReconnect = true;
                                break;
                            }
                            OnClosed?.Invoke(_ws.CloseStatus ?? WebSocketCloseStatus.Empty);
                            if (_ws.CloseStatus != null && _ws.CloseStatus != WebSocketCloseStatus.NormalClosure)
                            {
                                OnError?.Invoke(new Exception(_ws.CloseStatus + " " + _ws.CloseStatusDescription));
                            }
                        }

                        lastState = State;
                    }
                }
                catch (Exception ex)
                {
                    OnError?.Invoke(ex);
                }
                if (needsReconnect && !_reconnecting && !_disconnectCalled)
#pragma warning disable 4014
                {
                    DoReconnect();
                }
#pragma warning restore 4014
                _monitorRunning = false;
            });
        }