-
Notifications
You must be signed in to change notification settings - Fork 40
/
NatsConnection.Ping.cs
44 lines (37 loc) · 1.6 KB
/
NatsConnection.Ping.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System.Runtime.CompilerServices;
using NATS.Client.Core.Commands;
namespace NATS.Client.Core;
public partial class NatsConnection
{
/// <inheritdoc />
#if !NETSTANDARD
[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))]
#endif
public async ValueTask<TimeSpan> PingAsync(CancellationToken cancellationToken = default)
{
if (ConnectionState != NatsConnectionState.Open)
{
await ConnectAsync().AsTask().WaitAsync(cancellationToken).ConfigureAwait(false);
}
PingCommand pingCommand;
if (!_pool.TryRent(out pingCommand!))
{
pingCommand = new PingCommand(_pool);
}
pingCommand.Start();
await CommandWriter.PingAsync(pingCommand, cancellationToken).ConfigureAwait(false);
return await pingCommand.RunAsync().ConfigureAwait(false);
}
/// <summary>
/// Send PING command to writers channel waiting on the chanel if necessary.
/// This is to make sure the PING time window is not missed in case the writer
/// channel is full with other commands and we will wait to enqueue rather than
/// just trying which might not happen in time on a busy channel.
/// </summary>
/// <param name="cancellationToken">Cancels the Ping command</param>
/// <returns><see cref="ValueTask"/> representing the asynchronous operation</returns>
private ValueTask PingOnlyAsync(CancellationToken cancellationToken = default) =>
ConnectionState == NatsConnectionState.Open
? CommandWriter.PingAsync(new PingCommand(_pool), cancellationToken)
: default;
}