Skip to content

Commit be1e462

Browse files
committed
Improve ConcurrentUniqueBatchQueue
1 parent 3964f10 commit be1e462

File tree

1 file changed

+9
-20
lines changed

1 file changed

+9
-20
lines changed

Common/Services/BatchUpdate/BatchUpdateService.cs

Lines changed: 9 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
using System.Collections.Concurrent;
2-
using System.Timers;
1+
using System.Timers;
32
using Microsoft.EntityFrameworkCore;
43
using NRedisStack.RedisStackCommands;
54
using OpenShock.Common.Constants;
@@ -13,35 +12,25 @@ namespace OpenShock.Common.Services.BatchUpdate;
1312

1413
internal sealed class ConcurrentUniqueBatchQueue<TKey, TValue> where TKey : notnull
1514
{
16-
private readonly ReaderWriterLockSlim _lock = new();
17-
private readonly ConcurrentDictionary<TKey, TValue> _dictionary = new();
15+
private readonly Lock _lock = new();
16+
private Dictionary<TKey, TValue> _dictionary = new();
1817

1918
public void Enqueue(TKey key, TValue value)
2019
{
21-
_lock.EnterReadLock();
22-
try
20+
lock (_lock)
2321
{
2422
_dictionary[key] = value;
2523
}
26-
finally
27-
{
28-
_lock.ExitReadLock();
29-
}
3024
}
3125

32-
public KeyValuePair<TKey, TValue>[] DequeueAll()
26+
public Dictionary<TKey, TValue> DequeueAll()
3327
{
34-
_lock.EnterWriteLock();
35-
try
28+
lock (_lock)
3629
{
37-
var items = _dictionary.ToArray();
38-
_dictionary.Clear();
30+
var items = _dictionary;
31+
_dictionary = new Dictionary<TKey, TValue>();
3932
return items;
4033
}
41-
finally
42-
{
43-
_lock.ExitWriteLock();
44-
}
4534
}
4635
}
4736

@@ -81,7 +70,7 @@ private async void UpdateTimerOnElapsed(object? sender, ElapsedEventArgs eventAr
8170

8271
private async Task UpdateTokens()
8372
{
84-
var keys = _tokenLastUsed.DequeueAll().Select(x => x.Key).ToArray();
73+
var keys = _tokenLastUsed.DequeueAll().Keys.ToArray();
8574

8675
// Skip if there is nothing
8776
if (keys.Length < 1) return;

0 commit comments

Comments
 (0)