@@ -123,9 +123,30 @@ public void SetActiveReader(MySqlDataReader dataReader)
123123
124124 public void FinishQuerying ( )
125125 {
126+ bool clearConnection = false ;
126127 lock ( m_lock )
127128 {
128- VerifyState ( State . Querying , State . CancelingQuery ) ;
129+ if ( m_state == State . CancelingQuery )
130+ {
131+ m_state = State . ClearingPendingCancellation ;
132+ clearConnection = true ;
133+ }
134+ }
135+
136+ if ( clearConnection )
137+ {
138+ // KILL QUERY will kill a subsequent query if the command it was intended to cancel has already completed.
139+ // In order to handle this case, we issue a dummy query that will consume the pending cancellation.
140+ // See https://bugs.mysql.com/bug.php?id=45679
141+ var payload = new PayloadData ( new ArraySegment < byte > ( PayloadUtilities . CreateEofStringPayload ( CommandKind . Query , "DO SLEEP(0);" ) ) ) ;
142+ SendAsync ( payload , IOBehavior . Synchronous , CancellationToken . None ) . GetAwaiter ( ) . GetResult ( ) ;
143+ payload = ReceiveReplyAsync ( IOBehavior . Synchronous , CancellationToken . None ) . GetAwaiter ( ) . GetResult ( ) ;
144+ OkPayload . Create ( payload ) ;
145+ }
146+
147+ lock ( m_lock )
148+ {
149+ VerifyState ( State . Querying , State . ClearingPendingCancellation ) ;
129150 m_state = State . Connected ;
130151 m_activeReader = null ;
131152 m_activeCommand = null ;
@@ -311,7 +332,7 @@ private void VerifyConnected()
311332 {
312333 if ( m_state == State . Closed )
313334 throw new ObjectDisposedException ( nameof ( MySqlSession ) ) ;
314- if ( m_state != State . Connected && m_state != State . Querying && m_state != State . CancelingQuery && m_state != State . Closing )
335+ if ( m_state != State . Connected && m_state != State . Querying && m_state != State . CancelingQuery && m_state != State . ClearingPendingCancellation && m_state != State . Closing )
315336 throw new InvalidOperationException ( "MySqlSession is not connected." ) ;
316337 }
317338 }
@@ -667,6 +688,9 @@ private enum State
667688 // The session is connected to a server and the active query is being cancelled.
668689 CancelingQuery ,
669690
691+ // A cancellation is pending on the server and needs to be cleared.
692+ ClearingPendingCancellation ,
693+
670694 // The session is closing.
671695 Closing ,
672696
0 commit comments