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; }