/// <summary>Acquire and lock connection from a pool.</summary>
        /// <param name="cancellationToken">
        ///     The cancellation token.
        /// </param>
        /// <returns>
        ///     The <see cref="Task" />.
        /// </returns>
        private async Task <IAcquiredConnection> AcquireConnectionAsync(CancellationToken cancellationToken)
        {
            IAcquiredConnection  acquiredConnection;
            ITarantoolConnection newTarantoolConnection = null;

            lock (_connections)
            {
                var connection = _connections.FirstOrDefault(x => !x.IsAcquired);
                if (connection == null)
                {
                    newTarantoolConnection = new TarantoolConnection(_connectionOptions, 0);
                    _connections.Add(newTarantoolConnection);
                    connection = newTarantoolConnection;
                }

                acquiredConnection = new AcquiredConnection(connection);
            }

            if (newTarantoolConnection != null)
            {
                await PrepareNewConnectionAsync(newTarantoolConnection, cancellationToken).ConfigureAwait(false);
            }

            return(acquiredConnection);
        }
        /// <summary>Connect to Tarantool and watch for disconnection, remove from pool on disconnect.</summary>
        /// <param name="newConnection">The new connection.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The <see cref="Task" />.</returns>
        private async Task PrepareNewConnectionAsync(
            ITarantoolConnection newConnection,
            CancellationToken cancellationToken)
        {
            await newConnection.ConnectAsync(cancellationToken).ConfigureAwait(false);

            newConnection.OnDisconnected(
                () =>
            {
                lock (_connections)
                {
                    _connections.Remove(newConnection);
                    try
                    {
                        newConnection.Dispose();
                    }
                    catch
                    {
                        // ignored
                    }
                }
            });
        }
Exemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AcquiredConnection"/> class.
 /// Marks connection as acquired.
 /// </summary>
 /// <param name="connection">
 /// The connection.
 /// </param>
 internal AcquiredConnection(ITarantoolConnection connection)
 {
     _connection = connection;
     _connection.Acquire();
 }