Table of Contents

Class FlyweightCache<TKey, TValue>

Namespace
Kampute.HttpClient.Utilities
Assembly
Kampute.HttpClient.dll

Provides a thread-safe cache for efficiently retrieving and lazily adding key-value pairs.

public sealed class FlyweightCache<TKey, TValue> where TKey : notnull

Type Parameters

TKey

The type of keys used in the cache.

TValue

The type of values stored in the cache.

Inheritance
FlyweightCache<TKey, TValue>
Inherited Members

Remarks

This cache utilizes ConcurrentDictionary<TKey, TValue> to ensure thread-safe access while optimizing for high read scenarios and infrequent writes. Values are created on demand using a specified factory method when they are accessed and not already present, allowing for efficient memory usage and avoiding pre-population overhead.

Constructors

FlyweightCache(Func<TKey, TValue>)

Initializes a new instance of the FlyweightCache<TKey, TValue> class using a specified value factory.

public FlyweightCache(Func<TKey, TValue> valueFactory)

Parameters

valueFactory Func<TKey, TValue>

A delegate that defines the method to create values if the key does not exist in the cache.

Exceptions

ArgumentNullException

Thrown if the provided valueFactory is null.

FlyweightCache(Func<TKey, TValue>, IEqualityComparer<TKey>)

Initializes a new instance of the FlyweightCache<TKey, TValue> class using a specified value factory and key comparer.

public FlyweightCache(Func<TKey, TValue> valueFactory, IEqualityComparer<TKey> keyComparer)

Parameters

valueFactory Func<TKey, TValue>

A delegate that defines the method to create values if the key does not exist in the cache.

keyComparer IEqualityComparer<TKey>

The equality comparison implementation to use when comparing keys.

Exceptions

ArgumentNullException

Thrown if the provided valueFactory or keyComparer is null.

Properties

Count

Gets the number of key/value pairs contained in the cache.

public int Count { get; }

Property Value

int

The number of key/value pairs currently stored in the cache.

Methods

Clear()

Clears the cache.

public void Clear()

Contains(TKey)

Checks if the cache contains a value associated with the specified key.

public bool Contains(TKey key)

Parameters

key TKey

The key to check in the cache.

Returns

bool

true if the key exists in the cache; otherwise, false.

Get(TKey)

Retrieves a value for the specified key.

public TValue Get(TKey key)

Parameters

key TKey

The key whose value to retrieve.

Returns

TValue

The value associated with the specified key.