I've found an example in .Net documentation on how to implement AsyncCache. They suggest the following:
public class AsyncCache<TKey, TValue>
{
private readonly Func<TKey, Task<TValue>> _valueFactory;
private readonly ConcurrentDictionary<TKey, Lazy<Task<TValue>>> _map;
public AsyncCache(Func<TKey, Task<TValue>> valueFactory)
{
if (valueFactory == null) throw new ArgumentNullException("loader");
_valueFactory = valueFactory;
_map = new ConcurrentDictionary<TKey, Lazy<Task<TValue>>>();
}
public Task<TValue> this[TKey key]
{
get
{
if (key == null) throw new ArgumentNullException("key");
return _map.GetOrAdd(key, toAdd =>
new Lazy<Task<TValue>>(() => _valueFactory(toAdd))).Value;
}
}
}
Why can't we just use Task in _map dictionary without wrapping it in a Lazy? As for me, Task itself behaves like a Lazy from that point that it executes only once and then we can access the result by Result property or by awaiting it.
So, can anybody explain what is the purpose of using Lazy here? Thanks