Skip to content

Commit 2a5fb7b

Browse files
committed
fix: replace Dictionary with ConcurrentDictionary in DuplicateFinder hash cache for thread-safety
1 parent eefdb5f commit 2a5fb7b

1 file changed

Lines changed: 5 additions & 8 deletions

File tree

src/DeepPurge.Core/FileSystem/DuplicateFinder.cs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public class DuplicateFinder
3838
private const int FirstChunkBytes = 1 * 1024 * 1024;
3939
private const long MinFileBytes = 4 * 1024;
4040
private static readonly string CachePath = Path.Combine(DataPaths.Root, "hash-cache.json");
41-
private Dictionary<string, HashCacheEntry> _cache = new(StringComparer.OrdinalIgnoreCase);
41+
private ConcurrentDictionary<string, HashCacheEntry> _cache = new(StringComparer.OrdinalIgnoreCase);
4242

4343
public async Task<List<DuplicateGroup>> FindAsync(
4444
IEnumerable<string> roots,
@@ -303,11 +303,7 @@ private void UpdateCache(string path, ulong? headHash = null, ulong? fullHash =
303303
try
304304
{
305305
var fi = new FileInfo(path);
306-
if (!_cache.TryGetValue(path, out var entry))
307-
{
308-
entry = new HashCacheEntry { Size = fi.Length, LastWriteTicks = fi.LastWriteTimeUtc.Ticks };
309-
_cache[path] = entry;
310-
}
306+
var entry = _cache.GetOrAdd(path, _ => new HashCacheEntry());
311307
entry.Size = fi.Length;
312308
entry.LastWriteTicks = fi.LastWriteTimeUtc.Ticks;
313309
if (headHash.HasValue) entry.HeadHash = headHash.Value;
@@ -322,8 +318,9 @@ private void LoadCache()
322318
{
323319
if (!File.Exists(CachePath)) return;
324320
var json = File.ReadAllText(CachePath);
325-
_cache = JsonSerializer.Deserialize<Dictionary<string, HashCacheEntry>>(json)
326-
?? new(StringComparer.OrdinalIgnoreCase);
321+
var dict = JsonSerializer.Deserialize<Dictionary<string, HashCacheEntry>>(json);
322+
if (dict != null)
323+
_cache = new ConcurrentDictionary<string, HashCacheEntry>(dict, StringComparer.OrdinalIgnoreCase);
327324
}
328325
catch { _cache = new(StringComparer.OrdinalIgnoreCase); }
329326
}

0 commit comments

Comments
 (0)