-
Notifications
You must be signed in to change notification settings - Fork 217
Clean up MemoryCache and fix thread-safety issues #12440
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
DustinCampbell
merged 4 commits into
dotnet:main
from
DustinCampbell:clean-up-memorycache
Nov 7, 2025
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
52f0850
Adopt TestAccessor pattern for MemoryCache
DustinCampbell 959e2a4
Clean up and fix thread safety issues in MemoryCache
DustinCampbell 00b0d4f
Add more MemoryCache test coverage
DustinCampbell 3ceb688
Make MemoryCache test deterministic
DustinCampbell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
24 changes: 24 additions & 0 deletions
24
src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Utilities/MemoryCache`2.Entry.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Threading; | ||
|
|
||
| namespace Microsoft.CodeAnalysis.Razor.Utilities; | ||
|
|
||
| internal sealed partial class MemoryCache<TKey, TValue> where TKey : notnull | ||
| where TValue : class | ||
| { | ||
| private sealed class Entry(TValue value) | ||
| { | ||
| private long _lastAccessTicks = DateTime.UtcNow.Ticks; | ||
|
|
||
| public DateTime LastAccess => new(Volatile.Read(ref _lastAccessTicks)); | ||
| public TValue Value => value; | ||
|
|
||
| public void UpdateLastAccess() | ||
| { | ||
| Volatile.Write(ref _lastAccessTicks, DateTime.UtcNow.Ticks); | ||
| } | ||
| } | ||
| } |
34 changes: 34 additions & 0 deletions
34
...Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Utilities/MemoryCache`2.TestAccessor.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
|
|
||
| namespace Microsoft.CodeAnalysis.Razor.Utilities; | ||
|
|
||
| internal partial class MemoryCache<TKey, TValue> | ||
| where TKey : notnull | ||
| where TValue : class | ||
| { | ||
| internal TestAccessor GetTestAccessor() => new(this); | ||
|
|
||
| internal struct TestAccessor(MemoryCache<TKey, TValue> instance) | ||
| { | ||
| public event Action Compacted | ||
| { | ||
| add => instance._compactedHandler += value; | ||
| remove => instance._compactedHandler -= value; | ||
| } | ||
|
|
||
| public readonly bool TryGetLastAccess(TKey key, out DateTime result) | ||
| { | ||
| if (instance._map.TryGetValue(key, out var value)) | ||
| { | ||
| result = value.LastAccess; | ||
| return true; | ||
| } | ||
|
|
||
| result = default; | ||
| return false; | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
47 changes: 47 additions & 0 deletions
47
src/Razor/test/Microsoft.CodeAnalysis.Razor.Workspaces.Test/Utilities/MemoryCachePerfTest.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Diagnostics; | ||
| using System.Linq; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.AspNetCore.Razor.Test.Common; | ||
| using Microsoft.CodeAnalysis.Razor.Utilities; | ||
| using Xunit; | ||
| using Xunit.Abstractions; | ||
|
|
||
| namespace Microsoft.CodeAnalysis.Razor.Workspaces.Test.Utilities; | ||
|
|
||
| [CollectionDefinition(nameof(MemoryCachePerfTest), DisableParallelization = false)] | ||
| [Collection(nameof(MemoryCachePerfTest))] | ||
| public class MemoryCachePerfTest(ITestOutputHelper testOutput) : ToolingTestBase(testOutput) | ||
| { | ||
| [Fact] | ||
| public async Task HighFrequencyAccess_MaintainsPerformance() | ||
| { | ||
| var cache = new MemoryCache<string, IReadOnlyList<int>>(); | ||
| const string Key = "hot-key"; | ||
| cache.Set(Key, [1, 2, 3]); | ||
|
|
||
| const int AccessCount = 10_000; | ||
| var stopwatch = Stopwatch.StartNew(); | ||
|
|
||
| var tasks = Enumerable.Range(0, Environment.ProcessorCount) | ||
| .Select(x => Task.Run(() => | ||
| { | ||
| for (var i = 0; i < AccessCount / Environment.ProcessorCount; i++) | ||
| { | ||
| _ = cache.TryGetValue(Key, out _); | ||
| } | ||
| })) | ||
| .ToArray(); | ||
|
|
||
| await Task.WhenAll(tasks); | ||
| stopwatch.Stop(); | ||
|
|
||
| // Should complete reasonably quickly (adjust threshold as needed) | ||
| Assert.True(stopwatch.ElapsedMilliseconds < 1000, | ||
DustinCampbell marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| $"High-frequency access took too long: {stopwatch.ElapsedMilliseconds}ms"); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.