Skip to Content
TUtilityCaches, pools and queues

Caches, pools and queues

On this page

Memory caches

TUtility.Caching.MemoryCache<TKey, TValue> and string-keyed MemoryCache provide in-process caching. Generic keys and values avoid unnecessary conversions. Install TUtility.Core to run this example: two reads for the same device load the source only once.

using TUtility.Caching; using var cache = new MemoryCache<string, string>(StringComparer.Ordinal); var source = new Dictionary<string, string>(StringComparer.Ordinal) { ["P-001"] = "Pump" }; var loads = 0; foreach (var code in new[] { "P-001", "P-001" }) { if (!cache.TryGetValue(code, out var name)) { name = source[code]; loads++; cache.Set(code, name, expire: 60); } Console.WriteLine(name); } Console.WriteLine($"Loads: {loads}"); cache.Remove("P-001"); Console.WriteLine($"Cached after removal: {cache.TryGetValue("P-001", out _)}");

Expected output:

Pump Pump Loads: 1 Cached after removal: False
Setting / operationContract
Set(..., expire) / Add / GetOrAddInteger TTL in seconds; negative values use Expire
ExpireDefaults to 3600 seconds; a non-positive effective TTL does not expire
SetExpire / GetExpireUse TimeSpan
CapacityDefaults to 100000; enforced by periodic eviction
PeriodCleanup defaults to 60 seconds; its timer is established during construction

Capacity eviction runs during periodic cleanup. TryGetValue checks TTL, but its out value may contain stale data when it returns false; branch on the Boolean result. Count includes expired entries awaiting cleanup.

Generic GetOrAdd does not recheck existing entries’ TTL and may return expired values awaiting cleanup. Use TryGetValue → load → Set for expiry reloads. Both patterns may load concurrently more than once; coordinate by key for deduplication and avoid factory side effects. See async coordination.

SetExpire changes an entry’s lifetime. Assigning Period does not reconfigure the timer established by the constructor.

Caches retain references, do not clone values, and do not take general ownership of disposable values. Dispose host-owned cache instances during shutdown. Respect ownership of a shared static Instance.

Concurrent misses: recheck after acquiring a permit

Four requests share a WaitLock to coordinate one device’s loading. After acquiring a permit, waiting callers recheck the cache:

using TUtility; using TUtility.Caching; using var cache = new MemoryCache<string, string>(StringComparer.Ordinal); using var loadGate = new WaitLock(maxCount: 1); using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var source = new Dictionary<string, string>(StringComparer.Ordinal) { ["P-001"] = "Pump" }; var loads = 0; var tasks = Enumerable.Range(0, 4) .Select(_ => ReadDeviceAsync("P-001", cancellation.Token)).ToArray(); var values = await Task.WhenAll(tasks); Console.WriteLine($"Values: {string.Join(", ", values)}"); Console.WriteLine($"Source loads: {loads}"); Console.WriteLine($"Permit restored: {loadGate.CurrentCount == 1}"); /// <summary>只缓存成功结果;等待成功才释放许可,并在独占加载前复查有效缓存。</summary> async Task<string> ReadDeviceAsync(string code, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (cache.TryGetValue(code, out var cached) && cached is not null) return cached; await loadGate.WaitAsync(cancellationToken); try { cancellationToken.ThrowIfCancellationRequested(); if (cache.TryGetValue(code, out cached) && cached is not null) return cached; Interlocked.Increment(ref loads); await Task.Yield(); cancellationToken.ThrowIfCancellationRequested(); var value = source[code]; cache.Set(code, value, expire: 60); return value; } finally { loadGate.Release(); } }

Expected output:

Values: Pump, Pump, Pump, Pump Source loads: 1 Permit restored: True

Recheck inside the gate for a value stored by the previous caller. WaitAsync stays outside try; acquired permits are released in finally. Only successful results reach Set.

Pass the same cancellation token to database or network reads. Wait for all tasks before disposing the cache and gate.

This gate serializes misses for every key. Multi-key services can coordinate by key or a bounded set of groups, with a capacity limit on the lock map.

Keys include realm, configuration version and business identity. Invalidate after updates. See async coordination for permit waits and timeout overloads.

Object pools

ObjectPool<T> holds idle reusable objects. TryGet() may return null. The caller creates, resets and returns objects:

using System.Text; using TUtility; var pool = new ObjectPool<StringBuilder>(); var buffer = pool.TryGet() ?? new StringBuilder(); try { buffer.Append("P-001"); Console.WriteLine(buffer.ToString()); } finally { buffer.Clear(); pool.TryPut(buffer); }

The pool does not track borrowed objects. Return each object once and stop using it after return. TryPut reports acceptance. Callers can discard excessively large buffers. Review resource ownership before selecting DisposeObjectPool<T> or IdleObjectPool<T> for streams or connections.

Multiple producers, one consumer

UltraMpscQueue<T> supports concurrent producers through Enqueue and exactly one consumer through TryDequeue, DrainSpan or DrainArray. Keep peek and bulk-drain operations under the same consumer ownership.

This program waits for three producers, then drains from the current flow. Sorting makes the displayed result deterministic; it does not establish a fixed order between concurrent producers.

using TUtility; var queue = new UltraMpscQueue<int>(); await Task.WhenAll( Task.Run(() => queue.Enqueue(1)), Task.Run(() => queue.Enqueue(2)), Task.Run(() => queue.Enqueue(3))); var received = new List<int>(); while (queue.TryDequeue(out var item)) { received.Add(item); } received.Sort(); Console.WriteLine($"Received: {string.Join(", ", received)}"); Console.WriteLine($"Remaining: {queue.Count}");

Expected output:

Received: 1, 2, 3 Remaining: 0

The queue does not bound backlog or create a worker. While producers are active, TryDequeue returning false does not mean consumption is complete; Count and IsEmpty are concurrent observations. Perform the final drain after producers stop.

Diagnose performance and ownership problems

SymptomCheck
Four requests cause four source readsShared load coordination and a valid-cache recheck after acquiring the permit
Expired objects are returnedGeneric GetOrAdd bypassing TTL checks, or use of a failed TryGetValue output
Memory briefly grows beyond configured capacityPeriodic eviction, individual value sizes and application-held references or lists
Unrelated devices wait for one anotherAll misses sharing one global gate; choose scope against the source’s concurrency budget
Pooled data appears in another operationIncomplete reset, duplicate return or access after return
Healthy queue throughput with growing memoryProduction exceeding consumption; the queue has no backlog ceiling