KafkaNet.KafkaTcpSocket.ReEstablishConnectionAsync C# (CSharp) Method

ReEstablishConnectionAsync() private method

(Re-)establish the Kafka server connection. Assumes that the caller has already obtained the _clientLock
private ReEstablishConnectionAsync ( ) : Task
return Task
        private async Task<TcpClient> ReEstablishConnectionAsync()
        {
            var attempts = 1;
            var reconnectionDelay = DefaultReconnectionTimeout;
            _log.DebugFormat("No connection to:{0}.  Attempting to connect...", _endpoint);

            _client = null;

            while (_disposeToken.IsCancellationRequested == false && _maxRetry > attempts)
            {
                attempts++;
                try
                {
                    if (OnReconnectionAttempt != null) OnReconnectionAttempt(attempts);
                    _client = new TcpClient();

                    var connectTask = _client.ConnectAsync(_endpoint.Endpoint.Address, _endpoint.Endpoint.Port);
                    await Task.WhenAny(connectTask, _disposeTask).ConfigureAwait(false);

                    if (_disposeToken.IsCancellationRequested)
                        throw new ObjectDisposedException(string.Format("Object is disposing (KafkaTcpSocket for endpoint: {0})", Endpoint));

                    await connectTask;
                    if (!_client.Connected) throw new BrokerConnectionException(string.Format("Lost connection to server: {0}", _endpoint), _endpoint);
                    _log.DebugFormat("Connection established to:{0}.", _endpoint);

                    return _client;
                }
                catch (Exception ex)
                {
                    reconnectionDelay = reconnectionDelay * DefaultReconnectionTimeoutMultiplier;
                    reconnectionDelay = Math.Min(reconnectionDelay, (int)_maximumReconnectionTimeout.TotalMilliseconds);

                    _log.WarnFormat("Failed connection to:{0}.  Will retry in:{1} Exception{2}", _endpoint, reconnectionDelay, ex.Message);
                    if (_maxRetry < attempts)
                    {
                        throw;
                    }
                }

                await Task.Delay(TimeSpan.FromMilliseconds(reconnectionDelay), _disposeToken.Token).ConfigureAwait(false);
            }

            return _client;
        }