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.
return 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 follows:
tcs = new TaskCompletionSource<float>();
But we could make this easier and slightly better-performing:
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:
- Would the convenience make this feature worthwhile?
- 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)?
- 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.