Skip to content

Commit 4d6bc33

Browse files
committed
Handle race condition in OpenTcpSocketAsync. Fixes #476
1 parent c175893 commit 4d6bc33

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

src/MySqlConnector/Core/ServerSession.cs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -694,7 +694,7 @@ private async Task<bool> OpenTcpSocketAsync(ConnectionSettings cs, ILoadBalancer
694694
{
695695
tcpClient = new TcpClient(ipAddress.AddressFamily);
696696

697-
using (cancellationToken.Register(() => tcpClient?.Client?.Dispose()))
697+
using (cancellationToken.Register(() => tcpClient.Client?.Dispose()))
698698
{
699699
try
700700
{
@@ -727,17 +727,25 @@ private async Task<bool> OpenTcpSocketAsync(ConnectionSettings cs, ILoadBalancer
727727
}
728728
catch (ObjectDisposedException ex) when (cancellationToken.IsCancellationRequested)
729729
{
730+
SafeDispose(ref tcpClient);
730731
Log.Info("Session{0} connect timeout expired connecting to IpAddress {1} for HostName '{2}'", m_logArguments[0], ipAddress, hostName);
731732
throw new MySqlException("Connect Timeout expired.", ex);
732733
}
733734
}
734735
}
735736
catch (SocketException)
736737
{
737-
tcpClient?.Client?.Dispose();
738+
SafeDispose(ref tcpClient);
738739
continue;
739740
}
740741

742+
if (!tcpClient.Connected && cancellationToken.IsCancellationRequested)
743+
{
744+
SafeDispose(ref tcpClient);
745+
Log.Info("Session{0} connect timeout expired connecting to IpAddress {1} for HostName '{2}'", m_logArguments[0], ipAddress, hostName);
746+
throw new MySqlException("Connect Timeout expired.");
747+
}
748+
741749
HostName = hostName;
742750
m_tcpClient = tcpClient;
743751
m_socket = m_tcpClient.Client;

0 commit comments

Comments
 (0)