Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 30 additions & 20 deletions src/MongoDB.Driver/Core/Connections/TcpStreamFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ private void ConfigureConnectedSocket(Socket socket)
private void Connect(Socket socket, EndPoint endPoint, CancellationToken cancellationToken)
{
IAsyncResult connectOperation;

#if NET472
if (endPoint is DnsEndPoint dnsEndPoint)
{
// mono doesn't support DnsEndPoint in its BeginConnect method.
Expand All @@ -176,6 +176,9 @@ private void Connect(Socket socket, EndPoint endPoint, CancellationToken cancell
{
connectOperation = socket.BeginConnect(endPoint, null, null);
}
#else
connectOperation = socket.BeginConnect(endPoint, null, null);
#endif

WaitHandle.WaitAny([connectOperation.AsyncWaitHandle, cancellationToken.WaitHandle], _settings.ConnectTimeout);

Expand Down Expand Up @@ -203,31 +206,38 @@ private void Connect(Socket socket, EndPoint endPoint, CancellationToken cancell

private async Task ConnectAsync(Socket socket, EndPoint endPoint, CancellationToken cancellationToken)
{
var timeoutTask = Task.Delay(_settings.ConnectTimeout, cancellationToken);
var connectTask = socket.ConnectAsync(endPoint);

await Task.WhenAny(connectTask, timeoutTask).ConfigureAwait(false);

if (!connectTask.IsCompleted)
Task connectTask;
#if NET472
if (endPoint is DnsEndPoint dnsEndPoint)
{
try
{
socket.Dispose();
// should await on the read task to avoid UnobservedTaskException
await connectTask.ConfigureAwait(false);
} catch { }

cancellationToken.ThrowIfCancellationRequested();
throw new TimeoutException($"Timed out connecting to {endPoint}. Timeout was {_settings.ConnectTimeout}.");
// mono doesn't support DnsEndPoint in its ConnectAsync method.
connectTask = socket.ConnectAsync(dnsEndPoint.Host, dnsEndPoint.Port);
}

else
{
connectTask = socket.ConnectAsync(endPoint);
}
#else
connectTask = socket.ConnectAsync(endPoint);
#endif
try
{
await connectTask.ConfigureAwait(false);
await connectTask.WaitAsync(_settings.ConnectTimeout, cancellationToken).ConfigureAwait(false);
}
catch
catch (Exception ex)
{
try { socket.Dispose(); } catch { }
try
{
socket.Dispose();
connectTask.IgnoreExceptions();
}
catch { }

if (ex is TimeoutException)
{
throw new TimeoutException($"Timed out connecting to {endPoint}. Timeout was {_settings.ConnectTimeout}.");
}

throw;
}
}
Expand Down