How to Design Fluent Async Operations?

You could add an extension method overload which takes a Task or Task<T> to any method that you want to be chainable.

public static async Task<MyEntity> SecondStepAsync(this Task<MyEntity> entityTask)
{
    return (await entityTask).SecondStepAsync();
}

So you can just call await FirstStepAsync().SecondStepAsync()


Some of the answers that deal with continuations are forgetting that fluent works on concrete instances that are returned from each method.

I have written a sample implementation for you. The asynchronous work will start immediately on calling any of the DoX methods.

public class AsyncFluent
{
    /// Gets the task representing the fluent work.
    public Task Task { get; private set; }

    public AsyncFluent()
    {
        // The entry point for the async work.
        // Spin up a completed task to start with so that we dont have to do null checks    
        this.Task = Task.FromResult<int>(0);
    }

    /// Does A and returns the `this` current fluent instance.
    public AsyncFluent DoA()
    {
        QueueWork(DoAInternal);
        return this;
    }

    /// Does B and returns the `this` current fluent instance.
    public AsyncFluent DoB(bool flag)
    {
        QueueWork(() => DoBInternal(flag));
        return this;
    }

    /// Synchronously perform the work for method A.
    private void DoAInternal()
    {
        // do the work for method A
    }

    /// Synchronously perform the work for method B.
    private void DoBInternal(bool flag)
    {
        // do the work for method B
    }

    /// Queues up asynchronous work by an `Action`.
    private void QueueWork(Action work)
    {
        // queue up the work
        this.Task = this.Task.ContinueWith<AsyncFluent>(task =>
            {
                work();
                return this;
            }, TaskContinuationOptions.OnlyOnRanToCompletion);
    }
}

A better way would be to have deferred execution similar to LINQ.

You can have many methods that don't actually do anything, they just set some option or store some logic. And at the end have a few methods that actually execute all the other logic that was stored previously.

That way only a few methods need to be async and only a single one is used at the end of each chain.

Something like this:

var myEntity = await StartChain().StoreSomeLogic().StoreSomeOtherLogic().ExecuteAsync()

That's how, for example, the new async MongoDB C# driver works:

var results = await collection.Find(...).Project(...).Skip(...).Sort(...).ToListAsync();