FlyweightCache<TKey, TValue> Class

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

Definition

Provides a thread-safe cache that creates the value of a key on first use and returns the same value afterwards.
public sealed class FlyweightCache<TKey, TValue>
Inheritance
  • object
  • FlyweightCache<TKey, TValue>

Type Parameters

TKey
The type of keys used in the cache.
TValue
The type of values stored in the cache.

Remarks

Entries are never removed except by Clear(), so use the cache for a small, bounded set of keys. When two threads ask for a missing key at the same time, the factory can run twice, but both get the same value.

Constructors

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

Initializes a new instance of the FlyweightCache<TKey, TValue> class using a specified value factory.
public FlyweightCache<TKey, TValue>(Func<TKey, TValue> valueFactory)

Parameters

valueFactory Func<TKey, TValue>
The function that creates the value of a key.

Exceptions

ArgumentNullException
Thrown if valueFactory is null.

FlyweightCache<TKey, TValue>(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<TKey, TValue>(Func<TKey, TValue> valueFactory, IEqualityComparer<TKey> keyComparer)

Parameters

valueFactory Func<TKey, TValue>
The function that creates the value of a key.
keyComparer IEqualityComparer<TKey>
The comparer that decides whether two keys are equal.

Exceptions

ArgumentNullException
Thrown if valueFactory or keyComparer is null.

Properties

Count

Gets the number of cached values.
public int Count { get; }

Property Value

int
The number of keys in the cache.

Methods

Clear()

Removes all values from the cache.
public void Clear()

Contains(TKey)

Determines whether the cache has a value for a key.
public bool Contains(TKey key)

Parameters

key TKey
The key to check.

Returns

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

Get(TKey)

Returns the value of a key, creating it if the cache has none.
public TValue Get(TKey key)

Parameters

key TKey
The key whose value to return.

Returns

TValue
The cached value of key.