CacheUtility 1.0.5

There is a newer version of this package available.
See the version list below for details.
dotnet add package CacheUtility --version 1.0.5
                    
NuGet\Install-Package CacheUtility -Version 1.0.5
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CacheUtility" Version="1.0.5" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CacheUtility" Version="1.0.5" />
                    
Directory.Packages.props
<PackageReference Include="CacheUtility" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add CacheUtility --version 1.0.5
                    
#r "nuget: CacheUtility, 1.0.5"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=CacheUtility&version=1.0.5
                    
Install as a Cake Addin
#tool nuget:?package=CacheUtility&version=1.0.5
                    
Install as a Cake Tool

CacheUtility

A thread-safe, generic wrapper for System.Runtime.Caching that simplifies cache access and supports powerful caching patterns.

Overview

CacheUtility provides an easy-to-use abstraction over the standard .NET memory cache with additional features:

  • Automatic cache population
  • Various expiration strategies
  • Thread-safe operations
  • Support for cache groups
  • Dependency relationships between cache groups

Basic Usage

Retrieving or Creating Cached Items

The most common pattern is to request an item from the cache, providing a function to generate the item if it doesn't exist:

// Basic usage with default 30-minute sliding expiration
var result = CacheUtility.Get("MyKey", "MyGroupName", () => 
{
    return MyLongRunningTask();
});

// With custom sliding expiration
var result = CacheUtility.Get("MyKey", "MyGroupName", TimeSpan.FromHours(1), () => 
{
    return MyLongRunningTask();
});

// With absolute expiration
var result = CacheUtility.Get("MyKey", "MyGroupName", DateTime.Now.AddDays(1), () => 
{
    return MyLongRunningTask();
});

// With full customization
var result = CacheUtility.Get("MyKey", "MyGroupName", 
    DateTime.Now.AddDays(1), // Absolute expiration
    TimeSpan.FromMinutes(10), // Sliding expiration
    CacheItemPriority.Default, // Priority
    () => MyLongRunningTask());

Async Operations

For async operations, you can use the utility with async/await:

var result = await CacheUtility.Get("MyKey", "MyGroupName", async () => 
{
    return await MyLongRunningTaskAsync();
});

Cache Management

Removing Individual Items

Remove a specific item from the cache:

CacheUtility.Remove("MyKey", "MyGroupName");

Removing Multiple Items

Remove multiple items that contain specific strings:

CacheUtility.Remove(new List<string> { "UserProfile", "123" }, "UserData");
// This will remove any cache key containing both "UserProfile" and "123"

Group Operations

Remove an entire group of cached items:

CacheUtility.RemoveGroup("MyGroupName");

Remove multiple groups:

CacheUtility.RemoveGroup("GroupA", "GroupB", "GroupC");

Cache Dependencies

Set up dependencies between cache groups so that when one group is cleared, its dependent groups are also cleared:

// Set up dependencies
CacheUtility.SetDependencies("ParentGroup", "ChildGroup1", "ChildGroup2");

// Now when ParentGroup is removed, ChildGroup1 and ChildGroup2 will also be removed
CacheUtility.RemoveGroup("ParentGroup");

Global Cache Operations

Clear the entire cache:

CacheUtility.RemoveAll();

Clear the cache except for specific groups:

CacheUtility.RemoveAllButThese(new List<string> { "CriticalData", "ApplicationSettings" });

Advanced Examples

Caching User Data

// Cache user data with a sliding expiration
var userData = CacheUtility.Get($"User_{userId}", "UserProfiles", TimeSpan.FromMinutes(30), () =>
{
    return database.GetUserById(userId);
});

Caching Application Settings

// Cache application settings with absolute expiration
var settings = CacheUtility.Get("GlobalSettings", "AppConfig", DateTime.Now.AddHours(12), () =>
{
    return configurationService.LoadSettings();
});

Cascading Cache Invalidation

// Set up dependencies
CacheUtility.SetDependencies("UserData", "UserProfiles", "UserPreferences", "UserActivity");
CacheUtility.SetDependencies("UserProfiles", "ProfilePhotos");

// Now when UserData is cleared, all dependent caches are also cleared
CacheUtility.RemoveGroup("UserData");
// This will clear UserData, UserProfiles, ProfilePhotos, UserPreferences, and UserActivity

Best Practices

  1. Group Related Items: Use meaningful group names to organize related cache items.
  2. Consider Expiration Strategies: Choose between sliding expiration (reset on access) and absolute expiration (fixed time) based on your use case.
  3. Set Dependencies: Use cache dependencies to maintain consistency between related data.
  4. Use Short Keys: Keep your cache keys concise but descriptive.

Performance Considerations

  • The CacheUtility uses locks to ensure thread safety, but is designed to minimize lock contention.
  • Populate methods are only called once per cache miss, even under high concurrency.
  • Consider memory usage when caching large objects or collections.

When to Use Cache Groups vs. Key Prefixes

  • Cache Groups: Use when you need to invalidate multiple related items at once.
  • Key Prefixes: Use within your keys when you want to organize items but may need more granular control.

Memory Management

The CacheUtility is built on top of .NET's MemoryCache, which has built-in memory pressure detection. However, be mindful of:

  • Setting appropriate cache priorities
  • Using reasonable expiration times
  • Caching only necessary data

Thread Safety

All operations in CacheUtility are thread-safe. The implementation uses ReaderWriterLockSlim for efficient concurrent access and CacheLock for synchronizing modifications to the cache.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.9 126 6/19/2025
1.0.8 128 6/19/2025
1.0.6 127 6/19/2025
1.0.5 173 4/20/2025
1.0.4 208 4/16/2025
1.0.3 158 11/7/2024
1.0.2 115 11/7/2024
1.0.1 625 9/3/2023
1.0.0 612 9/3/2023

Support for .Net 9.0 and updated the README.md file