I have class:
public class LazyConcurrentDictionary<TKey, TValue>
{
private readonly ConcurrentDictionary<TKey, Lazy<TValue>> _concurrentDictionary;
public LazyConcurrentDictionary()
{
_concurrentDictionary = new ConcurrentDictionary<TKey, Lazy<TValue>>();
}
public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
{
var lazyResult = _concurrentDictionary.GetOrAdd(key,
k => new Lazy<TValue>(() => valueFactory(k), LazyThreadSafetyMode.ExecutionAndPublication));
return lazyResult.Value;
}
}
I want use this class for manage token. A token expired in 2 hours.
var dictionary = new LazyConcurrentDictionary<string, Lazy<Tuple<string, DateTime>>>();
var result = dictionary.GetOrAdd("80", k => new Lazy<Tuple<string, DateTime>>(() =>
{
return new Tuple<string, DateTime>(Guid.NewGuid().ToString(), DateTime.Now);
}));
For example for key 80 have value tuple with token and datetime now.
How do change code when time expired get new token?
best regards
Getting an access token generally implies a network call. In this scenario asynchronous programming is a win. So let's define a delegate that returns an access token asynchronously for a given key:
Then you can use a concurrent dictionary to cache the tokens. However you cannot store the tokens in the dictionary because the factory is asynchronous. You need to store
Task<AccessToken>. Futhermore, to avoid cache stampede becauseConcurrentDictionary.GetOrAddmay invoke serveral times the dictionary value factory function, you need to useLazyvalues. So, at the end, you need to storeLazy<Task<AccessToken>>values in the dictionary.With this in mind you can use the following
AccessTokenCacheclass that caches the tokens and removes expired ones at intervals: