All about Async/Await, System.Threading.Tasks, System.Collections.Concurrent, System.Linq, and more…
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>.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>();
But we could make this easier and slightly
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:
Please add - i needed that functionality in my code ( if (dataSourceX != null) return GetDataSourceTask() else Task.FromResult(emptyResult) ) -- this construct greatly simplified all the code logic, waiting, etc. I vote to definitely include it. P.S. It took me a very long time to even find this post - Task.FromResult would have been much more intuitive.
Looks great, but I would love some consistency in naming - particularly with Rx. What about Task.Return() to mirror Observable.Return()?
I just needed this feature and found this post via google...
I like the idea, don't know about the optimization, but since you are planning to add new methods to task (I think), then it's a good time to do it as opposed to use a custom extension method. And I'm interested in the exception one, at least to be able to give a "NotImplementedException" a "ObjectDisposedException" or an "ArgumentException" (and sons) which are usually trivial to check and throw.
So... how is this feature going.. about -99 yet?
Definitely we need it. It's extremely useful for unit testing and mocking asynch operations. In fact we already created our own class that can create tasks in certain state.
public static Task<T> RanToCompletion<T>(T value)
public static Task<T> Faulted<T>(Exception exception)
public static Task<T> Canceled<T>()
i have made an extension method that returns a completed Task in our system. we use it for when the contract or interface expexts a task, but the perticular implementation doest not support async operation.
i would personally find it useful to have such a method in the framework :)
Thanks for the great feedback, everyone!
How pleasant is to find at first search that the one's problem has been solved intelligently by others.
Same case: cached data!