For the complete documentation index, see llms.txt. This page is also available as Markdown.

Cache

MemoryCache in-process cache, expiration policy, dependency tokens, and eviction events.

MemoryCache is an in-process cache implementation in the Zongsoft.Caching namespace. It wraps Microsoft.Extensions.Caching.Memory.MemoryCache Source and adds Zongsoft-style expiration descriptions, dependency tokens, priorities, obsolescence events, and quantity limit reminders.

MemoryCache is suitable for caching in-process reconstructable data, such as metadata, descriptors, parsing results, or lightweight objects. Cross-process sharing, distributed consistency, and inter-service cache synchronization should use the concrete implementation of IDistributedCache.

Type Relationship

Type
Description

MemoryCache

In-process cache container providing read, write, delete, get or create, cleanup and event notification.

MemoryCacheOptions

Configure scan frequency and quantity limits; MemoryCache.Shared uses immutable options.

MemoryCacheScanner

Periodically call Compact(0) to trigger expired item scanning.

MemoryCache.Expiration

Describes sliding expiration, absolute expiration, or a combination of both.

CachePriority

Maps to underlying cache item priorities: Low, Normal, High, NeverRemove.

CacheEvictedEventArgs

Evicted event parameters, including key, value, elimination reason and status object.

CacheLimitedEventArgs

Limited event parameters, including the exceeded quantity and current quantity.

Create Cache

Discussions Indirectly use the framework's cache reuse mechanism through data accessors. The independent demonstration of the cache itself comes from Core's memorycache interactive program: frequency of one second, sliding expiration of thirty seconds, and quantity reminder threshold. You can create independent cache instances directly or use shared instances.

Source: framework/Zongsoft.Core/samples/memorycache/Program.cs (excerpt; see source for context).

Program.cs
const int FREQUENCY  = 1;
const int EXPIRATION = 30;
const int LIMIT      = 5;

using var cache = new MemoryCache(TimeSpan.FromSeconds(FREQUENCY), LIMIT);
using var scanner = new MemoryCacheScanner(cache);

cache.Limited += Cache_Limited;
cache.Evicted += Cache_Evicted;

MemoryCache.Shared is a global shared instance, and its Options is immutable and cannot be modified at runtime.

Read and Write

SetValue is used to write cache entries directly, GetValue and TryGetValue are used to read cache entries, and Remove is used to delete cache entries.

Source: framework/Zongsoft.Core/test/Caching/MemoryCacheTest.cs (excerpt; see source for context).

Use GetOrCreate or GetOrCreateAsync when "create without" semantics are required. These methods call the factory when a read misses; a concurrent miss does not mean that the factory must be executed only once, and it should not be relied upon to complete the only write in the business. Here is the real purpose of the data accessor provider: cache the created accessor and use its Disposed notification as a cache invalidation dependency.

Source: framework/Zongsoft.Core/src/Data/DataAccessProviderBase.cs (excerpt; see source for context).

Expiration Policy

MemoryCache.Expiration can express sliding expiration, absolute expiration, or both at the same time. The following table is a parameter form reference; the following actual example writes the terminal input text into the Key# sequence number, and uses the EXPIRATION constant and the Now attribute of the same type to record the status.

Writing method
Description

TimeSpan.FromMinutes(10)

Sliding expiration means that cache items will expire only if they are not accessed within a specified period of time.

DateTimeOffset.UtcNow.AddHours(1)

Absolute expiration means that the cached item expires after the specified time point.

(TimeSpan.FromMinutes(10), DateTimeOffset.UtcNow.AddHours(1))

Set sliding expiration and absolute expiration at the same time.

Source: framework/Zongsoft.Core/samples/memorycache/Program.cs (excerpt; see source for context).

Dependency Token

Cache entries can depend on IChangeToken. When the token changes, the cache item is marked as invalid and the eviction callback is triggered.

Source: framework/Zongsoft.Core/test/Caching/MemoryCacheTest.cs (excerpt; see source for context).

CancellationChangeToken in the example will convert the cancellation token into a cache dependency token.

The elimination reason corresponding to dependency failure is CacheEvictedReason.Depended.

Events

MemoryCache provides two events. The TestDependency above relies on the Cache_Evicted callback of the same test class to log the cause and wait for asynchronous notification; the entire fixture should be retained when reusing tests. Interactive examples actively clear in the Limited callback: this is the cleanup strategy selected by the example and is not automatically executed within the cache.

The meaning of the event is as follows:

Events
Trigger time

Evicted

Cache items are evicted due to expiration, dependency failure, deletion, replacement, or capacity pressure.

Limited

After setting or creating a cache entry, the current number exceeds MemoryCacheOptions.CountLimit.

Source: framework/Zongsoft.Core/samples/memorycache/Program.cs (excerpt; see source for context).

Clean and Scan

Compact is used to trigger underlying cache cleanup. Because the cache item is not necessarily removed from the underlying container immediately after it expires or the dependency becomes invalid, actively calling Compact(0) can prompt the cache to perform a scan.

MemoryCacheScanner encapsulates a timer and calls Compact(0) according to the MemoryCacheOptions.ScanFrequency cycle.

Source: framework/Zongsoft.Core/src/Caching/MemoryCacheScanner.cs (excerpt; see source for context).

Last updated