nats-io / nats.net.v1

The official C# Client for NATS
Apache License 2.0
646 stars 154 forks source link

Handling of unobserved tasks after connection opening timeout #916

Closed TobZip closed 1 month ago

TobZip commented 1 month ago

Tasks from failed NATS connections appeared when observing and logging unobserved task exception, even though the failed connections were handled, as the result of the connection task wasn't observed by e.g. using await or reading the task's Exception property.

This Pull Request changes that by observing the task exception, although the result is then ignored as NATS has already detected the failure as a timeout. The continueWith task executed after a connection timeout occurs will now check if there was an exception, preventing the TaskScheduler.UnobservedTaskException event from being triggered by an already handled connection failure.

This Pull Request also ensures the TCP client is explicitly closed or disposed even in case of a timeout. This resolves a race condition where the TCP client field typically is set to null before the client is closed or disposed.

A test case was added to ensure an unobserved task exception does not appear when connecting to a NATS server that does not accept connections (because it wasn't started).

That the TCP client now is closed or disposed even in case of a timeout was manually confirmed using breakpoints.

scottf commented 1 month ago

@TobZip Thank you for this contribution