Skip to content

Commit

Permalink
Fixed race condition between CloseConnector and OpenNewConnector (#3721)
Browse files Browse the repository at this point in the history
Fixes #3719

(cherry picked from commit 55c6ab2)
  • Loading branch information
vonzshik committed May 11, 2021
1 parent bf4e949 commit 952f277
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/Npgsql/ConnectorPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,7 @@ bool CheckIdleConnector([NotNullWhen(true)] NpgsqlConnector? connector)

// In case there's a waiting attempt on the channel, we write a null to the idle connector channel
// to wake it up, so it will try opening (and probably throw immediately)
// Statement order is important since we have synchronous completions on the channel.
IdleConnectorWriter.TryWrite(null);

throw;
Expand Down Expand Up @@ -399,10 +400,6 @@ void CloseConnector(NpgsqlConnector connector)
Log.Warn("Exception while closing connector", e, connector.Id);
}

// If a connector has been closed for any reason, we write a null to the idle connector channel to wake up
// a waiter, who will open a new physical connection
IdleConnectorWriter.TryWrite(null);

var i = 0;
for (; i < _max; i++)
if (Interlocked.CompareExchange(ref _connectors[i], null, connector) == connector)
Expand All @@ -414,6 +411,12 @@ void CloseConnector(NpgsqlConnector connector)

var numConnectors = Interlocked.Decrement(ref _numConnectors);
Debug.Assert(numConnectors >= 0);

// If a connector has been closed for any reason, we write a null to the idle connector channel to wake up
// a waiter, who will open a new physical connection
// Statement order is important since we have synchronous completions on the channel.
IdleConnectorWriter.TryWrite(null);

// Only turn off the timer one time, when it was this Close that brought Open back to _min.
if (numConnectors == _min)
DisablePruning();
Expand Down

0 comments on commit 952f277

Please sign in to comment.