Skip to content
Merged
Show file tree
Hide file tree
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
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,41 @@ 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 idea of the test: we are trying to connect to some host/port (non-localhost) that will definitely reject the connection,
// when specifying very small timeout leads us to the TimeoutException, but also we should ensure there is no Unobserved Task Exception happening.
var subject = new TcpStreamFactory(new TcpStreamSettings(connectTimeout: TimeSpan.FromMilliseconds(1)));
var host = IPAddress.Parse("1.1.1.1");
var port = 23456;
Copy link
Contributor

Choose a reason for hiding this comment

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

minor: maybe var enpdoint = new IPEndPoint(...) instead?

Copy link
Member Author

Choose a reason for hiding this comment

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

Will do, leftovers from usage of TcpListener


GC.Collect();
var unobservedTaskExceptionRaised = false;
EventHandler<UnobservedTaskExceptionEventArgs> eventHandler = (s, args) =>
{
unobservedTaskExceptionRaised = true;
};

TaskScheduler.UnobservedTaskException += eventHandler;

try
{
var exception = await Record.ExceptionAsync(() => subject.CreateStreamAsync(new IPEndPoint(host, port), 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