Skip to content

Commit

Permalink
Synchronize threads on Timer dispose
Browse files Browse the repository at this point in the history
  • Loading branch information
yaroslav-tykhonchuk committed Dec 18, 2023
1 parent 2d48b2c commit 0ad1f6b
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions AzureBatchQueue/TimerBatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@ internal class TimerBatch<T>
readonly ILogger logger;
readonly ConcurrentDictionary<string, BatchItem<T>> items;

Timer? timer;
readonly Timer timer;
BatchCompletedResult? completedResult;

bool flushTriggered;
readonly object locker = new();

public TimerBatch(BatchQueue<T> batchQueue, QueueMessage<T[]> msg, int maxDequeueCount, ILogger logger)
{
this.batchQueue = batchQueue;
Expand Down Expand Up @@ -85,9 +88,14 @@ async Task DoFlush()
/// </summary>
void DisposeTimer()
{
var timerCopy = timer;
timer = null;
timerCopy.Dispose();
lock (locker)
{
if (flushTriggered)
return;

flushTriggered = true;
timer.Dispose();
}
}

QueueMessage<T[]> Message()
Expand All @@ -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;
}

Expand Down

0 comments on commit 0ad1f6b

Please sign in to comment.