Skip to content
Merged
Changes from 2 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
44 changes: 26 additions & 18 deletions src/MongoDB.Driver/Core/Connections/TcpStreamFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -203,31 +203,39 @@ 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);
Task connectTask;

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

if (!connectTask.IsCompleted)
#if !NET472
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add same ifdef in sync Connect

connectTask = socket.ConnectAsync(endPoint);
#else
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 BeginConnect method.
connectTask = Task.Factory.FromAsync(socket.BeginConnect(dnsEndPoint.Host, dnsEndPoint.Port, null, null), socket.EndConnect);
}

else
{
connectTask = Task.Factory.FromAsync(socket.BeginConnect(endPoint, null, null), socket.EndConnect);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor: Probably regular socket.ConnectAsync can be used?

}
#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