Add ShouldNotStore flag to ICacheEntry for conditional cache suppression #120937
+215
−2
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.
Summary
Adds a new
ShouldNotStore
property toICacheEntry
that allows factory methods inGetOrCreate
andGetOrCreateAsync
to conditionally suppress storing the computed value in the cache. This enables scenarios where runtime conditions determine whether a value should be cached.Motivation
In some scenarios, the decision whether to cache a value can only be made during the factory execution. For example:
Previously, there was no way to prevent caching once
GetOrCreate
/GetOrCreateAsync
was called. This PR adds that capability.Usage Example
When
ShouldNotStore
is set totrue
, the factory's return value is provided to the caller but is not stored in the cache. Subsequent calls will re-execute the factory.Implementation Details
bool ShouldNotStore { get; set; }
property toICacheEntry
interfaceCacheEntry
class with a private backing fieldDispose()
andCommitWithTracking()
methods to check the flag before callingSetEntry()
GetOrCreate
/GetOrCreateAsync
- they already useusing
statements that callDispose()
Testing
Added 4 new tests to verify:
GetOrCreate
withShouldNotStore=true
doesn't cache and re-executes factoryGetOrCreateAsync
withShouldNotStore=true
doesn't cache and re-executes factoryGetOrCreate
without the flag (normal behavior) caches as expectedGetOrCreateAsync
without the flag (normal behavior) caches as expectedAll tests pass (137 total including 4 new tests).
Breaking Changes
None. This is a purely additive change that adds a new optional property to the public API.
Original prompt
This pull request was created as a result of the following prompt from Copilot chat.
💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.