Skip to content

Commit 3adaa8f

Browse files
authored
Fix task tracking (#764)
Keep a reference to long-running task to avoid potential GC.
1 parent d94f0ce commit 3adaa8f

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

src/NATS.Client.Core/NatsConnection.cs

+6-4
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ public partial class NatsConnection : INatsConnection
6161
private TimeSpan _backoff = TimeSpan.Zero;
6262
private string _lastAuthError = string.Empty;
6363
private bool _stopRetries;
64+
private Task? _publishEventsTask;
65+
private Task? _reconnectLoopTask;
6466

6567
public NatsConnection()
6668
: this(NatsOpts.Default)
@@ -97,7 +99,7 @@ public NatsConnection(NatsOpts opts)
9799
SingleWriter = false,
98100
SingleReader = true,
99101
});
100-
_ = Task.Run(PublishEventsAsync, _disposedCancellationTokenSource.Token);
102+
_publishEventsTask = Task.Run(PublishEventsAsync, _disposedCancellationTokenSource.Token);
101103
}
102104

103105
// events
@@ -410,7 +412,7 @@ private async ValueTask InitialConnectAsync()
410412
_pingTimerCancellationTokenSource = new CancellationTokenSource();
411413
StartPingTimer(_pingTimerCancellationTokenSource.Token);
412414
_waitForOpenConnection.TrySetResult();
413-
_ = Task.Run(ReconnectLoop);
415+
_reconnectLoopTask = Task.Run(ReconnectLoop);
414416
_eventChannel.Writer.TryWrite((NatsEvent.ConnectionOpened, new NatsEventArgs(url?.ToString() ?? string.Empty)));
415417
}
416418
}
@@ -709,7 +711,7 @@ private async void ReconnectLoop()
709711
_pingTimerCancellationTokenSource = new CancellationTokenSource();
710712
StartPingTimer(_pingTimerCancellationTokenSource.Token);
711713
_waitForOpenConnection.TrySetResult();
712-
_ = Task.Run(ReconnectLoop);
714+
_reconnectLoopTask = Task.Run(ReconnectLoop);
713715
_eventChannel.Writer.TryWrite((NatsEvent.ConnectionOpened, new NatsEventArgs(url.ToString())));
714716
}
715717
}
@@ -796,7 +798,7 @@ private async Task PublishEventsAsync()
796798
{
797799
_logger.LogError(NatsLogEvents.Connection, ex, "Error occured when publishing events");
798800
if (!_disposedCancellationTokenSource.IsCancellationRequested)
799-
_ = Task.Run(PublishEventsAsync, _disposedCancellationTokenSource.Token);
801+
_publishEventsTask = Task.Run(PublishEventsAsync, _disposedCancellationTokenSource.Token);
800802
}
801803
}
802804

0 commit comments

Comments
 (0)