Skip to content

Commit 00b0d4f

Browse files
Add more MemoryCache test coverage
Cover more concurrency and edge cases.
1 parent 959e2a4 commit 00b0d4f

File tree

3 files changed

+479
-13
lines changed

3 files changed

+479
-13
lines changed

src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Utilities/MemoryCache`2.TestAccessor.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ internal partial class MemoryCache<TKey, TValue>
1111
{
1212
internal TestAccessor GetTestAccessor() => new(this);
1313

14-
internal ref struct TestAccessor(MemoryCache<TKey, TValue> instance)
14+
internal struct TestAccessor(MemoryCache<TKey, TValue> instance)
1515
{
1616
public event Action Compacted
1717
{
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System;
5+
using System.Collections.Generic;
6+
using System.Diagnostics;
7+
using System.Linq;
8+
using System.Threading.Tasks;
9+
using Microsoft.AspNetCore.Razor.Test.Common;
10+
using Microsoft.CodeAnalysis.Razor.Utilities;
11+
using Xunit;
12+
using Xunit.Abstractions;
13+
14+
namespace Microsoft.CodeAnalysis.Razor.Workspaces.Test.Utilities;
15+
16+
[CollectionDefinition(nameof(MemoryCachePerfTest), DisableParallelization = false)]
17+
[Collection(nameof(MemoryCachePerfTest))]
18+
public class MemoryCachePerfTest(ITestOutputHelper testOutput) : ToolingTestBase(testOutput)
19+
{
20+
[Fact]
21+
public async Task HighFrequencyAccess_MaintainsPerformance()
22+
{
23+
var cache = new MemoryCache<string, IReadOnlyList<int>>();
24+
const string Key = "hot-key";
25+
cache.Set(Key, [1, 2, 3]);
26+
27+
const int AccessCount = 10_000;
28+
var stopwatch = Stopwatch.StartNew();
29+
30+
var tasks = Enumerable.Range(0, Environment.ProcessorCount)
31+
.Select(x => Task.Run(() =>
32+
{
33+
for (var i = 0; i < AccessCount / Environment.ProcessorCount; i++)
34+
{
35+
_ = cache.TryGetValue(Key, out _);
36+
}
37+
}))
38+
.ToArray();
39+
40+
await Task.WhenAll(tasks);
41+
stopwatch.Stop();
42+
43+
// Should complete reasonably quickly (adjust threshold as needed)
44+
Assert.True(stopwatch.ElapsedMilliseconds < 1000,
45+
$"High-frequency access took too long: {stopwatch.ElapsedMilliseconds}ms");
46+
}
47+
}

0 commit comments

Comments
 (0)