示例#1
0
        private async Task ConnectAsync(CancellationTokenSource reconnectCancelToken)
        {
            _connectionCancelToken = new CancellationTokenSource();
            _combinedCancelToken   = CancellationTokenSource.CreateLinkedTokenSource(_connectionCancelToken.Token, reconnectCancelToken.Token);
            CancelToken            = _combinedCancelToken.Token;

            _connectionPromise = new TaskCompletionSource <bool>();
            State = ConnectionState.Connecting;
            await _logger.InfoAsync("Connecting").ConfigureAwait(false);

            try
            {
                var readyPromise = new TaskCompletionSource <bool>();
                _readyPromise = readyPromise;

                //Abort connection on timeout
                var cancelToken = CancelToken;
                var _           = Task.Run(async() =>
                {
                    try
                    {
                        await Task.Delay(_connectionTimeout, cancelToken).ConfigureAwait(false);
                        readyPromise.TrySetException(new TimeoutException());
                    }
                    catch (OperationCanceledException) { }
                });

                await _onConnecting().ConfigureAwait(false);

                await _logger.InfoAsync("Connected").ConfigureAwait(false);

                State = ConnectionState.Connected;
                await _logger.DebugAsync("Raising Event").ConfigureAwait(false);

                await Connected.InvokeAsync(this, EventArgs.Empty).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Error(ex);
                throw;
            }
        }
 /// <summary>
 ///     Triggers the <see cref="Connected"/> event asynchronously.
 /// </summary>
 /// <param name="eventArgs">the event arguments</param>
 /// <returns>a task that represents the asynchronously operation.</returns>
 protected virtual Task OnConnectedAsync(ConnectedEventArgs eventArgs)
 => Connected.InvokeAsync(this, eventArgs);