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

前端 未结 4 1681
你的背包
你的背包 2021-02-08 13:33

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<         


        
4条回答
  •  半阙折子戏
    2021-02-08 14:08

    Does your getB have to be a method which returns Task rather than B?

    The problem is that ContinueWith is:

    public Task ContinueWith(
        Func, TNewResult> continuationFunction,
        CancellationToken cancellationToken
    )
    

    So in your case, because getB returns Task, you're passing in a Func, Task>, so TNewResult is Task.

    If you can change getB to just return a B given an A, that would work... or you could use:

    return ta.ContinueWith(a => getB(a.Result).Result);
    

    Then the lambda expression will be of type, Func, B> so ContinueWith will return a Task.

    EDIT: In C# 5 you could easily write:

    public async Task CombinedAsync()
    {
        A a = await getA();
        B b = await getB(a);
        return b;
    }
    

    ... so it's "just" a matter of working out what that ends up as. I suspect it's something like this, but with error handling:

    public Task CombinedAsync()
    {
        TaskCompletionSource source = new TaskCompletionSource();
        getA().ContinueWith(taskA => {
            A a = taskA.Result;
            Task taskB = getB(a);
            taskB.ContinueWith(t => source.SetResult(t.Result));
        });
        return source.Task;
    }
    

    Does that make sense?

提交回复
热议问题