Cold Tasks and TaskExtensions.Unwrap

前端 未结 1 1623
天命终不由人
天命终不由人 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 GetOrAddAsync(TKey key, Func> taskFunc)
    {
        Task> wrappedTask = new Task>(taskFunc);
        Task unwrappedTask = wrappedTask.Unwrap();
    
        Task 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)
提交回复
热议问题