Caching asynchronous operations

后端 未结 6 488
暖寄归人
暖寄归人 2020-12-28 16:40

I am looking for an elegant way of caching the results of my asynchronous operations.

I first had a synchronous method like this:

public String GetSt         


        
6条回答
  •  天命终不由人
    2020-12-28 17:29

    Another easy way to do this is to extend Lazy to be AsyncLazy, like so:

    public class AsyncLazy : Lazy>
    {
        public AsyncLazy(Func> taskFactory, LazyThreadSafetyMode mode) :
            base(() => Task.Factory.StartNew(() => taskFactory()).Unwrap(), mode)
        { }
    
        public TaskAwaiter GetAwaiter() { return Value.GetAwaiter(); }
    }
    

    Then you can do this:

    private readonly ConcurrentDictionary> _cache
        = new ConcurrentDictionary>();
    
    public async Task GetStuffAsync(string url)
    {
        return await _cache.GetOrAdd(url,
            new AsyncLazy(
                () => GetStuffInternalAsync(url),
                LazyThreadSafetyMode.ExecutionAndPublication));
    }
    

提交回复
热议问题