Skip to content

NTDLS/NTDLS.FastMemoryCache

Repository files navigation

NTDLS.FastMemoryCache

📦 Be sure to check out the NuGet pacakge: https://www.nuget.org/packages/NTDLS.FastMemoryCache

Provides fast and easy to use thread-safe partitioned memory cache for C# that helps manage the maximum size and track performance.

👀 This memory cache was developed to deal with caches containing large numbers of items. When working on a database server written in C# we found that we had significant contention around the cache. This project was the solution. It also allowed us to better manage the size of the cache and enforce max memory constraints. That said, if you are only caching a few dozen items - stick with IMemoryCache.

Quick and easy eample of a file cache:

Using the memory cache is easy, just initialize and upsert some values. You can also pass a configuration parameter to set max memory size, cache scavange rate and partition count.

readonly PartitionedMemoryCache _cache = new();

public string ReadFileFromDisk(string path)
{
    string cacheKey = path.ToLower();

    if (_cache.TryGet<string>(cacheKey, out var cachedObject))
    {
        return cachedObject;
    }

    string fileContents = File.ReadAllText(path);
    _cache.Upsert(cacheKey, fileContents, fileContents.Length * sizeof(char));
    return fileContents;
}

License

Apache-2.0

About

A fast, easy to use, thread-safe partitioned memory cache for .net that helps manage the memory size and track performance.

Topics

Resources

License

Stars

Watchers

Forks

Languages