Skip to content

Commit ef2a888

Browse files
committed
Fix exception in DisposeAsync. Fixes #305
If the connection is not in a known state (Connected or Failed), we'll just shut down the socket, which may be logged on the server as an aborted connection. This should prevent failure to shut down the session when an exception is thrown, leaking connections to the server.
1 parent 2d3cbcc commit ef2a888

File tree

1 file changed

+18
-16
lines changed

1 file changed

+18
-16
lines changed

src/MySqlConnector/Serialization/MySqlSession.cs

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -153,22 +153,28 @@ public async Task DisposeAsync(IOBehavior ioBehavior, CancellationToken cancella
153153
if (m_payloadHandler != null)
154154
{
155155
// attempt to gracefully close the connection, ignoring any errors (it may have been closed already by the server, etc.)
156+
State state;
156157
lock (m_lock)
157158
{
158-
VerifyState(State.Connected, State.Failed);
159-
m_state = State.Closing;
159+
if (m_state == State.Connected || m_state == State.Failed)
160+
m_state = State.Closing;
161+
state = m_state;
160162
}
161-
try
162-
{
163-
m_payloadHandler.StartNewConversation();
164-
await m_payloadHandler.WritePayloadAsync(QuitPayload.Create(), ioBehavior).ConfigureAwait(false);
165-
await m_payloadHandler.ReadPayloadAsync(m_payloadCache, ProtocolErrorBehavior.Ignore, ioBehavior).ConfigureAwait(false);
166-
}
167-
catch (IOException)
168-
{
169-
}
170-
catch (SocketException)
163+
164+
if (state == State.Closing)
171165
{
166+
try
167+
{
168+
m_payloadHandler.StartNewConversation();
169+
await m_payloadHandler.WritePayloadAsync(QuitPayload.Create(), ioBehavior).ConfigureAwait(false);
170+
await m_payloadHandler.ReadPayloadAsync(m_payloadCache, ProtocolErrorBehavior.Ignore, ioBehavior).ConfigureAwait(false);
171+
}
172+
catch (IOException)
173+
{
174+
}
175+
catch (SocketException)
176+
{
177+
}
172178
}
173179
}
174180
ShutdownSocket();
@@ -195,11 +201,7 @@ public async Task ConnectAsync(ConnectionSettings cs, IOBehavior ioBehavior, Can
195201
throw new MySqlException("Unable to connect to any of the specified MySQL hosts.");
196202
}
197203

198-
#if NETSTANDARD2_0
199-
var byteHandler = new StreamByteHandler(m_networkStream);
200-
#else
201204
var byteHandler = new SocketByteHandler(m_socket);
202-
#endif
203205
m_payloadHandler = new StandardPayloadHandler(byteHandler);
204206

205207
var payload = await ReceiveAsync(ioBehavior, cancellationToken).ConfigureAwait(false);

0 commit comments

Comments
 (0)