From 0ad1f6b38dd26bae57c94e160517e03e386b3717 Mon Sep 17 00:00:00 2001 From: yaroslavtykhonchuk Date: Mon, 18 Dec 2023 11:59:17 +0200 Subject: [PATCH] Synchronize threads on Timer dispose --- AzureBatchQueue/TimerBatch.cs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/AzureBatchQueue/TimerBatch.cs b/AzureBatchQueue/TimerBatch.cs index 00998da..8ed320d 100644 --- a/AzureBatchQueue/TimerBatch.cs +++ b/AzureBatchQueue/TimerBatch.cs @@ -12,9 +12,12 @@ internal class TimerBatch readonly ILogger logger; readonly ConcurrentDictionary> items; - Timer? timer; + readonly Timer timer; BatchCompletedResult? completedResult; + bool flushTriggered; + readonly object locker = new(); + public TimerBatch(BatchQueue batchQueue, QueueMessage msg, int maxDequeueCount, ILogger logger) { this.batchQueue = batchQueue; @@ -85,9 +88,14 @@ async Task DoFlush() /// void DisposeTimer() { - var timerCopy = timer; - timer = null; - timerCopy.Dispose(); + lock (locker) + { + if (flushTriggered) + return; + + flushTriggered = true; + timer.Dispose(); + } } QueueMessage Message() @@ -109,7 +117,12 @@ public BatchItemCompleteResult Complete(string itemId) if (!items.IsEmpty) return BatchItemCompleteResult.Completed; - timer?.Change(TimeSpan.Zero, Timeout.InfiniteTimeSpan); + lock (locker) + { + if (!flushTriggered) + timer.Change(TimeSpan.Zero, Timeout.InfiniteTimeSpan); + } + return BatchItemCompleteResult.BatchFullyProcessed; }