This is an automated email from the ASF dual-hosted git repository.
jinrongtong pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-clients.git
The following commit(s) were added to refs/heads/master by this push:
new 17ab1b40 feat(csharp): graceful PushConsumer shutdown aligned with Go
client (#1217)
17ab1b40 is described below
commit 17ab1b408b1bb444f5b9f2e297242dae9d6fa2fb
Author: guyinyou <[email protected]>
AuthorDate: Thu Apr 9 15:05:43 2026 +0800
feat(csharp): graceful PushConsumer shutdown aligned with Go client (#1217)
- After Stopping, cancel assignment scan and receive backoff only; defer
ACK/DLQ CTS cancellation
- Track inflight receive calls; wait up to request timeout plus long
polling timeout
- Wait until sum of per-queue cached messages reaches zero; warn every 10s
with current count
- Brief delay before cancelling consumption and ACK-related tokens, then
shutdown RPC client
- Pair inflight increments/decrements in ProcessQueue receive continuation
- Skip ScanAssignments when consumer is not Running
Co-authored-by: guyinyou <[email protected]>
---
csharp/rocketmq-client-csharp/ProcessQueue.cs | 67 +++++++++++-------
csharp/rocketmq-client-csharp/PushConsumer.cs | 98 ++++++++++++++++++++++++++-
2 files changed, 137 insertions(+), 28 deletions(-)
diff --git a/csharp/rocketmq-client-csharp/ProcessQueue.cs
b/csharp/rocketmq-client-csharp/ProcessQueue.cs
index 0c182d7e..44d72278 100644
--- a/csharp/rocketmq-client-csharp/ProcessQueue.cs
+++ b/csharp/rocketmq-client-csharp/ProcessQueue.cs
@@ -247,38 +247,55 @@ namespace Org.Apache.Rocketmq
Interlocked.Exchange(ref _activityTime, DateTime.UtcNow.Ticks);
- var task = _consumer.ReceiveMessage(request, _mq,
longPollingTimeout);
- task.ContinueWith(t =>
+ _consumer.NotifyReceiveMessageStarted();
+ try
{
- if (t.IsFaulted)
- {
- string nextAttemptId = null;
- if (t.Exception is { InnerException: RpcException {
StatusCode: StatusCode.DeadlineExceeded } })
- {
- nextAttemptId = request.AttemptId;
- }
-
- Logger.LogError(t.Exception, $"Exception raised during
message reception, mq={_mq}," +
- $"
attemptId={request.AttemptId}, nextAttemptId={nextAttemptId}," +
- $" clientId={clientId}");
- OnReceiveMessageException(t.Exception, nextAttemptId);
- }
- else
+ var task = _consumer.ReceiveMessage(request, _mq,
longPollingTimeout);
+ task.ContinueWith(t =>
{
try
{
- var result = t.Result;
- OnReceiveMessageResult(result);
+ if (t.IsFaulted)
+ {
+ string nextAttemptId = null;
+ if (t.Exception is { InnerException:
RpcException { StatusCode: StatusCode.DeadlineExceeded } })
+ {
+ nextAttemptId = request.AttemptId;
+ }
+
+ Logger.LogError(t.Exception, $"Exception
raised during message reception, mq={_mq}," +
+ $"
attemptId={request.AttemptId}, nextAttemptId={nextAttemptId}," +
+ $"
clientId={clientId}");
+ OnReceiveMessageException(t.Exception,
nextAttemptId);
+ }
+ else
+ {
+ try
+ {
+ var result = t.Result;
+ OnReceiveMessageResult(result);
+ }
+ catch (Exception ex)
+ {
+ // Should never reach here.
+ Logger.LogError($"[Bug] Exception raised
while handling receive result, mq={_mq}," +
+ $" endpoints={endpoints},
clientId={clientId}, exception={ex}");
+ OnReceiveMessageException(ex, attemptId);
+ }
+ }
}
- catch (Exception ex)
+ finally
{
- // Should never reach here.
- Logger.LogError($"[Bug] Exception raised while
handling receive result, mq={_mq}," +
- $" endpoints={endpoints},
clientId={clientId}, exception={ex}");
- OnReceiveMessageException(ex, attemptId);
+ _consumer.NotifyReceiveMessageFinished();
}
- }
- }, TaskContinuationOptions.ExecuteSynchronously);
+ }, TaskContinuationOptions.ExecuteSynchronously);
+ }
+ catch (Exception ex)
+ {
+ _consumer.NotifyReceiveMessageFinished();
+ Logger.LogError(ex, $"Exception raised during message
reception, mq={_mq}, clientId={clientId}");
+ OnReceiveMessageException(ex, attemptId);
+ }
}
catch (Exception ex)
{
diff --git a/csharp/rocketmq-client-csharp/PushConsumer.cs
b/csharp/rocketmq-client-csharp/PushConsumer.cs
index c46523f5..5d246079 100644
--- a/csharp/rocketmq-client-csharp/PushConsumer.cs
+++ b/csharp/rocketmq-client-csharp/PushConsumer.cs
@@ -60,6 +60,13 @@ namespace Org.Apache.Rocketmq
private readonly CancellationTokenSource _changeInvisibleDurationCts;
private readonly CancellationTokenSource
_forwardMsgToDeadLetterQueueCts;
+ private int _inflightReceiveCount;
+
+ /// <summary>Poll interval for shutdown waits and post-drain ACK grace
delay (aligned to 1s).</summary>
+ private static readonly TimeSpan ShutdownStepDelay =
TimeSpan.FromSeconds(1);
+
+ private static readonly TimeSpan ShutdownCacheDrainWarnInterval =
TimeSpan.FromSeconds(10);
+
/// <summary>
/// The caller is supposed to have validated the arguments and handled
throwing exception or
/// logging warnings already, so we avoid repeating args check here.
@@ -123,19 +130,36 @@ namespace Org.Apache.Rocketmq
GC.SuppressFinalize(this);
}
+ /// <summary>
+ /// Shutdown order (aligned with golang PushConsumer GracefulStop):
+ /// 1. Stopping: no new receive requests; cancel assignment scan and
receive backoff scheduling.
+ /// 2. Wait inflight receive requests finished or timeout (request
timeout + long polling timeout).
+ /// 3. Wait all locally cached messages drained (listener + async
ack/evict); warn every 10s with count.
+ /// 4. One-second delay for async ack.
+ /// 5. Cancel consumption and rpc-side retry tokens, then shutdown
client (RPC).
+ /// </summary>
protected override async Task Shutdown()
{
try
{
State = State.Stopping;
Logger.LogInformation($"Begin to shutdown the rocketmq push
consumer, clientId={ClientId}");
+ _scanAssignmentCts.Cancel();
_receiveMsgCts.Cancel();
+
+ Logger.LogInformation($"Waiting for the inflight receive
requests to be finished, clientId={ClientId}");
+ await WaitInflightReceiveFinishedAsync().ConfigureAwait(false);
+
+ await WaitCachedMessagesDrainedAsync().ConfigureAwait(false);
+
+ await Task.Delay(ShutdownStepDelay).ConfigureAwait(false);
+
+ _consumptionCts.Cancel();
_ackMsgCts.Cancel();
_changeInvisibleDurationCts.Cancel();
_forwardMsgToDeadLetterQueueCts.Cancel();
- _scanAssignmentCts.Cancel();
- await base.Shutdown();
- _consumptionCts.Cancel();
+
+ await base.Shutdown().ConfigureAwait(false);
Logger.LogInformation($"Shutdown the rocketmq push consumer
successfully, clientId={ClientId}");
State = State.Terminated;
}
@@ -146,6 +170,69 @@ namespace Org.Apache.Rocketmq
}
}
+ internal void NotifyReceiveMessageStarted()
+ {
+ Interlocked.Increment(ref _inflightReceiveCount);
+ }
+
+ internal void NotifyReceiveMessageFinished()
+ {
+ Interlocked.Decrement(ref _inflightReceiveCount);
+ }
+
+ private int GetTotalCachedMessageCount()
+ {
+ var sum = 0;
+ foreach (var kv in _processQueueTable)
+ {
+ sum += kv.Value.CachedMessagesCount();
+ }
+
+ return sum;
+ }
+
+ private async Task WaitInflightReceiveFinishedAsync()
+ {
+ var maxWait = _clientConfig.RequestTimeout +
_pushSubscriptionSettings.GetLongPollingTimeout();
+ var deadline = DateTime.UtcNow + maxWait;
+ while (Interlocked.Add(ref _inflightReceiveCount, 0) > 0)
+ {
+ if (DateTime.UtcNow >= deadline)
+ {
+ Logger.LogWarning(
+ "Timeout waiting for all inflight receive requests to
be finished, clientId={ClientId}, inflightReceiveCount={Inflight}",
+ ClientId, Interlocked.Add(ref _inflightReceiveCount,
0));
+ break;
+ }
+
+ await Task.Delay(ShutdownStepDelay).ConfigureAwait(false);
+ }
+
+ if (Interlocked.Add(ref _inflightReceiveCount, 0) <= 0)
+ {
+ Logger.LogInformation($"All inflight receive requests have
been finished, clientId={ClientId}");
+ }
+ }
+
+ private async Task WaitCachedMessagesDrainedAsync()
+ {
+ var nextWarnUtc = DateTime.UtcNow + ShutdownCacheDrainWarnInterval;
+ while (GetTotalCachedMessageCount() > 0)
+ {
+ await Task.Delay(ShutdownStepDelay).ConfigureAwait(false);
+ var now = DateTime.UtcNow;
+ if (now < nextWarnUtc)
+ {
+ continue;
+ }
+
+ Logger.LogWarning(
+ "Shutdown waiting for local cached messages to drain,
cachedMessageCount={Cached}, clientId={ClientId}",
+ GetTotalCachedMessageCount(), ClientId);
+ nextWarnUtc = now + ShutdownCacheDrainWarnInterval;
+ }
+ }
+
private ConsumeService CreateConsumerService()
{
if (_pushSubscriptionSettings.IsFifo())
@@ -200,6 +287,11 @@ namespace Org.Apache.Rocketmq
internal void ScanAssignments()
{
+ if (State != State.Running)
+ {
+ return;
+ }
+
try
{
Logger.LogDebug($"Start to scan assignments periodically,
clientId={ClientId}");