Commit 47fe376
authored
Fix race condition in MemoryCache.Compact() (#12434)
## Summary
Fixes #12430
This PR resolves a race condition in `MemoryCache<TKey,
TValue>.Compact()` that was causing intermittent test failures.
## The Problem
The `Compact()` method was enumerating a `ConcurrentDictionary` directly
while other threads could simultaneously modify it:
```csharp
var kvps = _dict.OrderBy(x => x.Value.LastAccess).ToArray();
```
This violated thread-safety expectations and caused `ArgumentException`
during concurrent operations.
## The Solution
Add an initial `.ToArray()` call to create a snapshot before sorting:
```csharp
var kvps = _dict.ToArray().OrderBy(x => x.Value.LastAccess).ToArray();
```
This ensures we operate on a stable snapshot rather than the live
dictionary, preventing concurrent modifications from disrupting the LINQ
enumeration.
## Impact
- Eliminates race condition without requiring additional locking
- Minimal performance overhead (one extra array allocation)
- Resolves intermittent test failures in
`Microsoft.CodeAnalysis.Razor.Utilities.MemoryCacheTest.ConcurrentSets_DoesNotThrow`File tree
1 file changed
+1
-1
lines changed- src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Utilities
1 file changed
+1
-1
lines changedLines changed: 1 addition & 1 deletion
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
64 | 64 | | |
65 | 65 | | |
66 | 66 | | |
67 | | - | |
| 67 | + | |
68 | 68 | | |
69 | 69 | | |
70 | 70 | | |
| |||
0 commit comments