Lazy <T> target in this MSDN example

I read about this asynchronous article from MSDN , but I cannot figure out the purpose Lazy<T>in this example.

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;
        }
    }
}

From what I understand, when you call .Valuefrom Lazy<T>, then it will call the constructor inside. From the example, this is called right away, so why add Lazy<T>?

+4
source share
2 answers

Suppose you change it to not use it Lazy<T>.

public class AsyncCache<TKey, TValue>
{
    private readonly Func<TKey, Task<TValue>> _valueFactory;
    private readonly ConcurrentDictionary<TKey, Task<TValue>> _map;

    public AsyncCache(Func<TKey, Task<TValue>> valueFactory)
    {
        if (valueFactory == null) throw new ArgumentNullException("loader");
        _valueFactory = valueFactory;
        _map = new ConcurrentDictionary<TKey, Task<TValue>>();
    }

    public Task<TValue> this[TKey key]
    {
        get
        {
            if (key == null) throw new ArgumentNullException("key");
            return _map.GetOrAdd(key, toAdd => _valueFactory(toAdd));
        }
    }
}

See notes in documentation:

GetOrAdd , addValueFactory , / ​​ .

, _valueFactory , .

, Lazy<T>? Lazy<Task<TValue>> , GetOrAdd . , Value. , _valueFactory .

, , . AsyncCache<string, byte[]> cache, lambda url => DownloadFile(url), , cache[myUrl] .

+5

GetOrAdd, . .

:

, . GetOrAdd, GetOrAdd. . , - , get. , . Lazy, _valueFactory (toAdd) .

0

All Articles