caching the result from a [n async] factory method iff it doesn't throw

后端 未结 4 989
北海茫月
北海茫月 2020-11-29 10:35

UPDATE: Heavily revised after @usr pointed out I\'d incorrectly assumed Lazy\'s default thread safety mode was LazyThreadSafetyMode.PublicationOn

4条回答
  •  一向
    一向 (楼主)
    2020-11-29 10:51

    For now, I am using this:

    public class CachedAsync
    {
        readonly Func> _taskFactory;
        T _value;
    
        public CachedAsync(Func> taskFactory)
        {
            _taskFactory = taskFactory;
        }
    
        public TaskAwaiter GetAwaiter() { return Fetch().GetAwaiter(); }
    
        async Task Fetch()
        {
            if (_value == null)
                _value = await _taskFactory();
            return _value;
        }
    }
    

    While it works in my scenario (I don't have multiple triggering threads etc.), it's hardly elegant and doesn't provide thread-safe coordination of either

    • a single attempt in progress a la LazyThreadSafetyMode.ExecutionAndPublication OR
    • a stable result after >= 1 success a la LazyThreadSafetyMode.PublicationOnly

提交回复
热议问题