-
Notifications
You must be signed in to change notification settings - Fork 4.9k
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
[Proposal] use Timer in MemoryCache #45842
Closed
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
dd6f6d3
don't get current time and check if scan for expired items should be …
adamsitnik c62b676
remove duplicated code from tests
adamsitnik 1ca3e9a
update tests: background activity is not required anymore
adamsitnik e498ae8
update tests: don't use the default expirationScanFrequency as these …
adamsitnik 1ca7ab4
introduce CanExpire flag
adamsitnik 38cff0e
don't ask for current time if the entry that has been found can not b…
adamsitnik d2397e1
based on profiling apply or revert some micro optimizations
adamsitnik 14b3513
Merge remote-tracking branch 'upstream/master' into memoryCacheTimer
adamsitnik 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
This file contains 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
This file contains 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 |
---|---|---|
|
@@ -4,9 +4,7 @@ | |
using System; | ||
using System.Collections.Concurrent; | ||
using System.Collections.Generic; | ||
using System.Runtime.CompilerServices; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Microsoft.Extensions.Internal; | ||
using Microsoft.Extensions.Logging; | ||
using Microsoft.Extensions.Logging.Abstractions; | ||
|
@@ -24,10 +22,10 @@ public class MemoryCache : IMemoryCache | |
|
||
private readonly MemoryCacheOptions _options; | ||
private readonly ConcurrentDictionary<object, CacheEntry> _entries; | ||
private readonly System.Timers.Timer _timer; | ||
|
||
private long _cacheSize; | ||
private bool _disposed; | ||
private DateTimeOffset _lastExpirationScan; | ||
|
||
/// <summary> | ||
/// Creates a new <see cref="MemoryCache"/> instance. | ||
|
@@ -63,7 +61,9 @@ public MemoryCache(IOptions<MemoryCacheOptions> optionsAccessor, ILoggerFactory | |
_options.Clock = new SystemClock(); | ||
} | ||
|
||
_lastExpirationScan = _options.Clock.UtcNow; | ||
_timer = new System.Timers.Timer(Math.Max(1, _options.ExpirationScanFrequency.TotalMilliseconds)); | ||
_timer.Elapsed += OnTimerElapsed; | ||
_timer.Start(); | ||
Comment on lines
+64
to
+66
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is bad for testability. Any timing mechanism needs to be abstracted for the unit tests. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I agree, but it's still doable |
||
} | ||
|
||
/// <summary> | ||
|
@@ -211,8 +211,6 @@ internal void SetEntry(CacheEntry entry) | |
RemoveEntry(priorEntry); | ||
} | ||
} | ||
|
||
StartScanForExpiredItemsIfNeeded(utcNow); | ||
} | ||
|
||
/// <inheritdoc /> | ||
|
@@ -221,39 +219,34 @@ public bool TryGetValue(object key, out object result) | |
ValidateCacheKey(key); | ||
CheckDisposed(); | ||
|
||
DateTimeOffset utcNow = _options.Clock.UtcNow; | ||
if (!_entries.TryGetValue(key, out CacheEntry entry)) | ||
{ | ||
result = null; | ||
return false; | ||
} | ||
|
||
if (_entries.TryGetValue(key, out CacheEntry entry)) | ||
if (entry.CanExpire) | ||
{ | ||
// Check if expired due to expiration tokens, timers, etc. and if so, remove it. | ||
// Allow a stale Replaced value to be returned due to concurrent calls to SetExpired during SetEntry. | ||
if (!entry.CheckExpired(utcNow) || entry.EvictionReason == EvictionReason.Replaced) | ||
DateTimeOffset utcNow = _options.Clock.UtcNow; | ||
if (entry.EvictionReason != EvictionReason.Replaced && entry.CheckExpired(utcNow)) | ||
{ | ||
entry.LastAccessed = utcNow; | ||
result = entry.Value; | ||
|
||
if (entry.CanPropagateOptions()) | ||
{ | ||
// When this entry is retrieved in the scope of creating another entry, | ||
// that entry needs a copy of these expiration tokens. | ||
entry.PropagateOptions(CacheEntryHelper.Current); | ||
} | ||
|
||
StartScanForExpiredItemsIfNeeded(utcNow); | ||
RemoveEntry(entry); | ||
|
||
return true; | ||
result = null; | ||
return false; | ||
} | ||
else | ||
|
||
entry.LastAccessed = utcNow; | ||
if (entry.CanPropagateOptions()) | ||
{ | ||
// TODO: For efficiency queue this up for batch removal | ||
RemoveEntry(entry); | ||
// When this entry is retrieved in the scope of creating another entry, | ||
// that entry needs a copy of these expiration tokens. | ||
entry.PropagateOptions(CacheEntryHelper.Current); | ||
} | ||
} | ||
|
||
StartScanForExpiredItemsIfNeeded(utcNow); | ||
|
||
result = null; | ||
return false; | ||
result = entry.Value; | ||
return true; | ||
} | ||
|
||
/// <inheritdoc /> | ||
|
@@ -272,8 +265,6 @@ public void Remove(object key) | |
entry.SetExpired(EvictionReason.Removed); | ||
entry.InvokeEvictionCallbacks(); | ||
} | ||
|
||
StartScanForExpiredItemsIfNeeded(_options.Clock.UtcNow); | ||
} | ||
|
||
private void RemoveEntry(CacheEntry entry) | ||
|
@@ -292,30 +283,13 @@ internal void EntryExpired(CacheEntry entry) | |
{ | ||
// TODO: For efficiency consider processing these expirations in batches. | ||
RemoveEntry(entry); | ||
StartScanForExpiredItemsIfNeeded(_options.Clock.UtcNow); | ||
} | ||
|
||
// Called by multiple actions to see how long it's been since we last checked for expired items. | ||
// If sufficient time has elapsed then a scan is initiated on a background task. | ||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
private void StartScanForExpiredItemsIfNeeded(DateTimeOffset utcNow) | ||
{ | ||
if (_options.ExpirationScanFrequency < utcNow - _lastExpirationScan) | ||
{ | ||
ScheduleTask(utcNow); | ||
} | ||
|
||
void ScheduleTask(DateTimeOffset utcNow) | ||
{ | ||
_lastExpirationScan = utcNow; | ||
Task.Factory.StartNew(state => ScanForExpiredItems((MemoryCache)state), this, | ||
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); | ||
} | ||
} | ||
private void OnTimerElapsed(object sender, System.Timers.ElapsedEventArgs e) => ScanForExpiredItems(this); | ||
|
||
private static void ScanForExpiredItems(MemoryCache cache) | ||
{ | ||
DateTimeOffset now = cache._lastExpirationScan = cache._options.Clock.UtcNow; | ||
DateTimeOffset now = cache._options.Clock.UtcNow; | ||
foreach (CacheEntry entry in cache._entries.Values) | ||
{ | ||
if (entry.CheckExpired(now)) | ||
|
@@ -483,6 +457,10 @@ protected virtual void Dispose(bool disposing) | |
GC.SuppressFinalize(this); | ||
} | ||
|
||
_timer.Stop(); | ||
_timer.Elapsed -= OnTimerElapsed; | ||
_timer.Dispose(); | ||
|
||
_disposed = true; | ||
} | ||
} | ||
|
This file contains 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
36 changes: 36 additions & 0 deletions
36
src/libraries/Microsoft.Extensions.Caching.Memory/tests/Infrastructure/CacheFactory.cs
This file contains 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,36 @@ | ||
// 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 Microsoft.Extensions.Caching.Memory; | ||
|
||
namespace Microsoft.Extensions.Internal | ||
{ | ||
internal static class CacheFactory | ||
{ | ||
internal static IMemoryCache CreateCache() | ||
{ | ||
return CreateCache(new SystemClock()); | ||
} | ||
|
||
internal static IMemoryCache CreateCache(ISystemClock clock) | ||
{ | ||
return new MemoryCache(new MemoryCacheOptions() | ||
{ | ||
Clock = clock, | ||
}); | ||
} | ||
|
||
internal static IMemoryCache CreateCache(ISystemClock clock, TimeSpan expirationScanFrequency) | ||
{ | ||
var options = new MemoryCacheOptions() | ||
{ | ||
Clock = clock, | ||
ExpirationScanFrequency = expirationScanFrequency, | ||
}; | ||
|
||
return new MemoryCache(options); | ||
} | ||
} | ||
} |
This file contains 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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Besides the abstraction thing, why not use
System.Threading.Timer
? It should have less overhead, asSystem.Timers.Timer
also relies onThreading.Timer
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's right, nothing should be using System.Timers.Timer.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've used this particular timer because it was the first one VS has suggested ;)
I wanted to have a proof of concept to get some numbers and get feedback before I invest more in the implementation.