public async ValueTask <ServerSession> GetSessionAsync(MySqlConnection connection, IOBehavior ioBehavior, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            // if all sessions are used, see if any have been leaked and can be recovered
            // check at most once per second (although this isn't enforced via a mutex so multiple threads might block
            // on the lock in RecoverLeakedSessions in high-concurrency situations
            if (m_sessionSemaphore.CurrentCount == 0 && unchecked (((uint)Environment.TickCount) - m_lastRecoveryTime) >= 1000u)
            {
                Log.Warn("{0} is empty; recovering leaked sessions", m_logArguments);
                RecoverLeakedSessions();
            }

            if (ConnectionSettings.MinimumPoolSize > 0)
            {
                await CreateMinimumPooledSessions(ioBehavior, cancellationToken).ConfigureAwait(false);
            }

            // wait for an open slot (until the cancellationToken is cancelled, which is typically due to timeout)
            Log.Debug("{0} waiting for an available session", m_logArguments);
            if (ioBehavior == IOBehavior.Asynchronous)
            {
                await m_sessionSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
            }
            else
            {
                m_sessionSemaphore.Wait(cancellationToken);
            }

            try
            {
                // check for a waiting session
                ServerSession session = null;
                lock (m_sessions)
                {
                    if (m_sessions.Count > 0)
                    {
                        session = m_sessions.First.Value;
                        m_sessions.RemoveFirst();
                    }
                }
                if (session != null)
                {
                    Log.Debug("{0} found an existing session; checking it for validity", m_logArguments);
                    bool reuseSession;

                    if (session.PoolGeneration != m_generation)
                    {
                        Log.Debug("{0} discarding session due to wrong generation", m_logArguments);
                        reuseSession = false;
                    }
                    else
                    {
                        if (ConnectionSettings.ConnectionReset)
                        {
                            reuseSession = await session.TryResetConnectionAsync(ConnectionSettings, ioBehavior, cancellationToken).ConfigureAwait(false);
                        }
                        else
                        {
                            reuseSession = await session.TryPingAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
                        }
                    }

                    if (!reuseSession)
                    {
                        // session is either old or cannot communicate with the server
                        Log.Warn("{0} Session{1} is unusable; destroying it", m_logArguments[0], session.Id);
                        AdjustHostConnectionCount(session, -1);
                        await session.DisposeAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        // pooled session is ready to be used; return it
                        session.OwningConnection = new WeakReference <MySqlConnection>(connection);
                        int leasedSessionsCountPooled;
                        lock (m_leasedSessions)
                        {
                            m_leasedSessions.Add(session.Id, session);
                            leasedSessionsCountPooled = m_leasedSessions.Count;
                        }
                        if (Log.IsDebugEnabled())
                        {
                            Log.Debug("{0} returning pooled Session{1} to caller; m_leasedSessions.Count={2}", m_logArguments[0], session.Id, leasedSessionsCountPooled);
                        }
                        return(session);
                    }
                }

                // create a new session
                session = new ServerSession(this, m_generation, Interlocked.Increment(ref m_lastSessionId));
                if (Log.IsInfoEnabled())
                {
                    Log.Info("{0} no pooled session available; created new Session{1}", m_logArguments[0], session.Id);
                }
                await session.ConnectAsync(ConnectionSettings, m_loadBalancer, ioBehavior, cancellationToken).ConfigureAwait(false);

                AdjustHostConnectionCount(session, 1);
                session.OwningConnection = new WeakReference <MySqlConnection>(connection);
                int leasedSessionsCountNew;
                lock (m_leasedSessions)
                {
                    m_leasedSessions.Add(session.Id, session);
                    leasedSessionsCountNew = m_leasedSessions.Count;
                }
                if (Log.IsDebugEnabled())
                {
                    Log.Debug("{0} returning new Session{1} to caller; m_leasedSessions.Count={2}", m_logArguments[0], session.Id, leasedSessionsCountNew);
                }
                return(session);
            }
            catch
            {
                m_sessionSemaphore.Release();
                throw;
            }
        }
        public async Task <ServerSession> GetSessionAsync(MySqlConnection connection, IOBehavior ioBehavior, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            // if all sessions are used, see if any have been leaked and can be recovered
            // check at most once per second (although this isn't enforced via a mutex so multiple threads might block
            // on the lock in RecoverLeakedSessions in high-concurrency situations
            if (m_sessionSemaphore.CurrentCount == 0 && unchecked (((uint)Environment.TickCount) - m_lastRecoveryTime) >= 1000u)
            {
                RecoverLeakedSessions();
            }

            if (m_connectionSettings.MinimumPoolSize > 0)
            {
                await CreateMinimumPooledSessions(ioBehavior, cancellationToken).ConfigureAwait(false);
            }

            // wait for an open slot (until the cancellationToken is cancelled, which is typically due to timeout)
            if (ioBehavior == IOBehavior.Asynchronous)
            {
                await m_sessionSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
            }
            else
            {
                m_sessionSemaphore.Wait(cancellationToken);
            }

            try
            {
                // check for a waiting session
                ServerSession session = null;
                lock (m_sessions)
                {
                    if (m_sessions.Count > 0)
                    {
                        session = m_sessions.First.Value;
                        m_sessions.RemoveFirst();
                    }
                }
                if (session != null)
                {
                    bool reuseSession;

                    if (session.PoolGeneration != m_generation)
                    {
                        reuseSession = false;
                    }
                    else
                    {
                        if (m_connectionSettings.ConnectionReset)
                        {
                            reuseSession = await session.TryResetConnectionAsync(m_connectionSettings, ioBehavior, cancellationToken).ConfigureAwait(false);
                        }
                        else
                        {
                            reuseSession = await session.TryPingAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
                        }
                    }

                    if (!reuseSession)
                    {
                        // session is either old or cannot communicate with the server
                        AdjustHostConnectionCount(session, -1);
                        await session.DisposeAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        // pooled session is ready to be used; return it
                        session.OwningConnection = new WeakReference <MySqlConnection>(connection);
                        lock (m_leasedSessions)
                            m_leasedSessions.Add(session.Id, session);
                        return(session);
                    }
                }

                // create a new session
                session = new ServerSession(this, m_generation, Interlocked.Increment(ref m_lastId));
                await session.ConnectAsync(m_connectionSettings, m_loadBalancer, ioBehavior, cancellationToken).ConfigureAwait(false);

                AdjustHostConnectionCount(session, 1);
                session.OwningConnection = new WeakReference <MySqlConnection>(connection);
                lock (m_leasedSessions)
                    m_leasedSessions.Add(session.Id, session);
                return(session);
            }
            catch
            {
                m_sessionSemaphore.Release();
                throw;
            }
        }