Skip to content
Merged
Show file tree
Hide file tree
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
6 changes: 5 additions & 1 deletion src/MongoDB.Driver/Core/Connections/TcpStreamFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,11 @@ private async Task ConnectAsync(Socket socket, EndPoint endPoint, CancellationTo

if (!connectTask.IsCompleted)
{
try { socket.Dispose(); } catch { }
try
{
connectTask.IgnoreExceptions();
socket.Dispose();
} catch { }

cancellationToken.ThrowIfCancellationRequested();
throw new TimeoutException($"Timed out connecting to {endPoint}. Timeout was {_settings.ConnectTimeout}.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,43 @@ public void CreateStream_should_connect_to_a_running_server_and_return_a_non_nul
stream.Should().NotBeNull();
}

[Fact]
public async Task CreateStream_should_not_produce_unobserved_exceptions_on_timeout()
{
// The purpose of this test is to attempt a connection that will reliably be rejected and throw exception the connection.
// By specifying a very short timeout, we expect a TimeoutException to occur before the connection exception.
// This test ensures that the connection exception is observed.
var subject = new TcpStreamFactory(new TcpStreamSettings(connectTimeout: TimeSpan.FromMilliseconds(1)));
var endpoint = new IPEndPoint(IPAddress.Parse("1.1.1.1"), 23456);

GC.Collect();
GC.WaitForPendingFinalizers();
var unobservedTaskExceptionRaised = false;

EventHandler<UnobservedTaskExceptionEventArgs> eventHandler = (s, args) =>
{
unobservedTaskExceptionRaised = true;
};

TaskScheduler.UnobservedTaskException += eventHandler;

try
{
var exception = await Record.ExceptionAsync(() => subject.CreateStreamAsync(endpoint, CancellationToken.None));
exception.Should().BeOfType<TimeoutException>();

Thread.Sleep(100);
GC.Collect();
GC.WaitForPendingFinalizers();
}
finally
{
TaskScheduler.UnobservedTaskException -= eventHandler;
}

unobservedTaskExceptionRaised.Should().BeFalse();
}

[Theory]
[ParameterAttributeData]
public void SocketConfigurator_can_be_used_to_set_keepAlive(
Expand Down