Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid NullReferenceException in TcpClient.EndConnect #899

Merged
merged 1 commit into from
Jul 8, 2024
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
6 changes: 3 additions & 3 deletions src/NATS.Client/Connection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -394,16 +394,17 @@ public virtual void open(Srv s, Options options)
if (!task.Wait(TimeSpan.FromMilliseconds(options.Timeout)))
{
nce = new NATSConnectionException("timeout");
task.ContinueWith(t => close(client));
Copy link
Collaborator

Choose a reason for hiding this comment

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

This I understand. The task is still running even though we aren't waiting for it. Since we timed-out we don't want the connection, so close it.

}
}
catch (Exception e)
{
nce = new NATSConnectionException(e.Message);
close(client);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Isn't it possible that the same thing happens? Maybe a better question is when would an exception be thrown.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

If an exception is thrown here, it means that the task is completed, and that it ended in an exception.
That's why we can safely dispose the TcpClient

Copy link
Collaborator

Choose a reason for hiding this comment

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

But if the task of making the tcp client failed, is there anything to safely close?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It disposes the TcpClient and its underlying Socket in a timely manner, after the connection failed.
If not disposed here, it is bound to be disposed at some point by the GC because the reference is not rooted, but it is always better to avoid unpredictable behaviors.

}

if (nce != null)
{
close(client);
client = null;
throw nce;
}
Expand Down Expand Up @@ -435,11 +436,10 @@ private static bool remoteCertificateValidation(
public virtual void close(TcpClient c)
{
#if NET46
c?.Close();
c?.Close();
#else
c?.Dispose();
#endif
c = null;
}

public void makeTLS()
Expand Down
Loading