Skip to content

Commit 29d8e35

Browse files
committed
Fix potential race condition in FinishQuerying. Fixes #1341
If TryStartCancel were called between the two 'lock' blocks, the session could be put into an unexpected state. Instead, perform all state updates in the first 'lock' instead of deferring cleanup work. This should also improve efficiency for the common (not cancelled) path. Signed-off-by: Bradley Grainger <[email protected]>
1 parent e132a64 commit 29d8e35

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

src/MySqlConnector/Core/ServerSession.cs

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -296,14 +296,23 @@ public void StartQuerying(ICancellableCommand command)
296296
public void FinishQuerying()
297297
{
298298
EnteringFinishQuerying(m_logger, Id, m_state);
299-
bool clearConnection = false;
299+
var clearConnection = false;
300300
lock (m_lock)
301301
{
302+
// entering this method, we expect to be in Querying, CancelingQuery, or Failed state
302303
if (m_state == State.CancelingQuery)
303304
{
304305
m_state = State.ClearingPendingCancellation;
305306
clearConnection = true;
306307
}
308+
else
309+
{
310+
if (m_state is State.Querying)
311+
m_state = State.Connected;
312+
else
313+
VerifyState(State.Failed);
314+
ActiveCommandId = 0;
315+
}
307316
}
308317

309318
if (clearConnection)
@@ -318,15 +327,13 @@ public void FinishQuerying()
318327
payload = ReceiveReplyAsync(IOBehavior.Synchronous, CancellationToken.None).GetAwaiter().GetResult();
319328
#pragma warning restore CA2012
320329
OkPayload.Verify(payload.Span, this);
321-
}
322330

323-
lock (m_lock)
324-
{
325-
if (m_state is State.Querying or State.ClearingPendingCancellation)
331+
lock (m_lock)
332+
{
333+
VerifyState(State.ClearingPendingCancellation);
326334
m_state = State.Connected;
327-
else
328-
VerifyState(State.Failed);
329-
ActiveCommandId = 0;
335+
ActiveCommandId = 0;
336+
}
330337
}
331338
}
332339

0 commit comments

Comments
 (0)