bikeman868
bikeman868

Reputation: 2637

Chaining a Task returned by a function in a library

The async...await in the code below feels wrong to me but I can't see a better alternative.

My actual code is much more complicated of course, this is a contrived example to illustrate the situation.

Note that in the real code, the Send method is implemented in a library, so I can't change its signature.

The idea is that SendAsync returns a task that completes after the sending data task has completed, but the function that gets the data and the function that sends the data are both async.

using System;
using System.Threading.Tasks;

internal class Example
{
    public Task SendAsync()
    {
        return GetData()
            .ContinueWith(async serialize => await Send(serialize.Result));
    }

    private Task<Dto> GetData()
    {
        return Task.FromResult(new Dto { SomeProperty = "Test"});
    }

    private Task Send(Dto dto)
    {
        return Task.Run(() => Console.WriteLine(dto.SomeProperty));
    }

    private class Dto
    {
        public string SomeProperty{ get; set; }
    }
}

Upvotes: 0

Views: 61

Answers (2)

Fabio
Fabio

Reputation: 32455

You can "treat" asynchronous methods as synchronous when one method depends on result of another.

public async Task SendAsync()
{
    var data = await GetData();

    await Send(data);
}

With await next line of code will be executed when Task returned by the method is complete.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062955

Seeing ContinueWith is usually a bad sign. Consider instead:

public async Task SendAsync()
{
    await Send(await GetData());
}

(Note: IMO all the methods here should be named with the Async suffix)

Upvotes: 3

Related Questions