Creating pre-completed Tasks



We’ve been considering adding support for creating completed
Tasks from an existing result.  Here’s a
prototypical example of where this could be valuable.


Task<float> ComputeAsync(…)
    if (!resultIsCached)
Task<float>.Factory.StartNew(() => Compute());
        // return a Task<float> with
the cached result

The method usually returns a Task<float> that
represents some compute-intensive operation that will be done asynchronously.  However, the greater code has the ability to
cache results from previous operations, so there’s a chance that the requested
result is already available.  If that’s
the case, we just want to return a completed Task with the cached result.  Note that this can be done in .NET 4 as


tcs = new TaskCompletionSource<float>();
return tcs.Task;

But we could make this easier and slightly


return Task.FromResult(cachedResult);

So your input would help. 
If you’ve got a minute, feel free to answer the following questions
and/or provide any other thoughts you have:

  1. Would the convenience make this feature worthwhile?
  2. If you have code that resembles this example, is performance a huge concern (to the point that shaving a few allocations and interlocked operations off of the creation of a pre-completed Task would help)?
  3. What about support for creating other pre-completed Tasks, e.g. creating a pre-canceled Task or one from an existing Exception?  Details regarding the scenario would help here.




Leave a comment