I don't know if I am thinking in the wrong way about TPL, but I have difficulty understanding how to obtain the following:
I have two functions
Task<A> getA() { ... }
Task<B> getB(A a) { ... }
This seems to occur often: I can asyncronously get an A. And given an A, I can asynchronously get a B.
I can't figure out the correct way to chain these functions together in TPL.
Here is one attempt:
Task<B> Combined()
{
Task<A> ta = getA();
Task<Task<B>> ttb = ta.ContinueWith(a => getB(a.Result));
return ttb.ContinueWith(x => x.Result.Result);
}
The ContinueWith
is where I get confused. The returned type is a "double-Task", Task<Task<B>>
. This somehow just seems wrong to me.
UPDATE 2011-09-30:
By coincidence I found the extension method TaskExtensions.Unwrap
that operates on a Task<Task<T>>
to give a Task<T>
.
So until we get C# 5.0, I can do ta.ContinueWith(a=>...).UnWrap() in situations like this where the continuation itself returns a task.
While the accepted answer would probably work
Task<B> Combined()
{
Task<A> ta = getA();
Task<B> ttb = ta.ContinueWith(a => getB(a.Result)).Unwrap();
return ttb;
}
Is a much more elegant way to implement this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With