Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining two functions () -> Task<A> and A->Task<B>

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.

like image 556
Bjarke Ebert Avatar asked Sep 22 '11 11:09

Bjarke Ebert


1 Answers

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.

like image 152
Yaur Avatar answered Sep 28 '22 08:09

Yaur