Skip to content

Commit

Permalink
Change connection task error handling. (#873)
Browse files Browse the repository at this point in the history
  • Loading branch information
scottf authored Mar 7, 2024
1 parent f7a537a commit c4dd08b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
21 changes: 14 additions & 7 deletions src/NATS.Client/Connection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -388,17 +388,24 @@ public virtual void open(Srv s, Options options)
client.Client.DualMode = true;

var task = client.ConnectAsync(s.Url.Host, s.Url.Port);
// avoid raising TaskScheduler.UnobservedTaskException if the timeout occurs first
task.ContinueWith(t =>
NATSConnectionException nce = null;
try
{
GC.KeepAlive(t.Exception);
close(client);
}, TaskContinuationOptions.OnlyOnFaulted);
if (!task.Wait(TimeSpan.FromMilliseconds(options.Timeout)))
if (!task.Wait(TimeSpan.FromMilliseconds(options.Timeout)))
{
nce = new NATSConnectionException("timeout");
}
}
catch (Exception e)
{
nce = new NATSConnectionException(e.Message);
}

if (nce != null)
{
close(client);
client = null;
throw new NATSConnectionException("timeout");
throw nce;
}

client.NoDelay = false;
Expand Down
5 changes: 4 additions & 1 deletion src/Samples/JetStreamStarter/JetStreamStarter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@
// limitations under the License.

using System;
using System.Threading;
using NATS.Client;
using NATS.Client.Internals;
using NATS.Client.JetStream;
using NATS.Client.KeyValue;

namespace NATSExamples
{
Expand Down Expand Up @@ -42,7 +45,7 @@ static void Main(string[] args)
{
Console.WriteLine("Connection closed.");
};

Console.WriteLine($"Connecting to '{opts.Url}'");

using (IConnection c = new ConnectionFactory().CreateConnection(opts))
Expand Down

0 comments on commit c4dd08b

Please sign in to comment.