Cold Tasks and TaskExtensions.Unwrap

前端 未结 1 1622
天命终不由人
天命终不由人 2021-01-01 03:42

I\'ve got a caching class that uses cold (unstarted) tasks to avoid running the expensive thing multiple times.

public class AsyncConcurrentDictionary

        
相关标签:
1条回答
  • 2021-01-01 04:46

    All you need to do is to keep the Task before unwrapping it around and start that:

    public Task<TValue> GetOrAddAsync(TKey key, Func<Task<TValue>> taskFunc)
    {
        Task<Task<TValue>> wrappedTask = new Task<Task<TValue>>(taskFunc);
        Task<TValue> unwrappedTask = wrappedTask.Unwrap();
    
        Task<TValue> cachedTask = base.GetOrAdd(key, unwrappedTask);
    
        if (cachedTask == unwrappedTask)
            wrappedTask.Start();
    
        return cachedTask;
    }
    

    Usage:

    cache.GetOrAddAsync(
        "key", async () =>
        {
            var r = await AsyncOperation();
            return r.FastSynchronousTransform();
        });
    
    0 讨论(0)
提交回复
热议问题