How to Design Fluent Async Operations?

梦想与她 提交于 2019-12-03 12:15:41
Gusdor

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();

One of the options is to declare and use the following generic extension methods:

public static TR Pipe<T, TR>(this T target, Func<T, TR> func) =>
    func(target);

public static async Task<TR> PipeAsync<T, TR>(this Task<T> target, Func<T, TR> func) =>
    func(await target);

public static async Task<TR> PipeAsync<T, TR>(this Task<T> target, Func<T, Task<TR>> func) =>
    await func(await target);

These utilities allow to represent the chain of asynchronous calls in such way:

MyEntity Xx = await FirstStepAsync()
    .PipeAsync(async firstResult => await firstResult.SecondStepAsync())
    .PipeAsync(async secondResult => await secondResult.ThirdStepAsync());

Resulting code may look more verbose, however it is easier to expand the chain, since there are no nested brackets.

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()

await is basically shorthand for ContinueWith, a method on a Task object (I'm simplifying here, but that's the basic concept). If you're trying to build a fluent syntax, consider using extension methods that receive Tasks and use ContinueWith to chain them:

public Task FirstStep()
{
     return Task.Run(/* whatever */);
}

public static Task SecondStep (this Task previousStep)
{
    return previousStep.ContinueWith(task => { /* whatver */  };
}

Now you can call await FirstStep().SecondStep(), and await the final result. Each method essentially adds another ContinueWith step.

If you want to make it more type safe, inherit a MyFluentTask from Task, and return that instead of a regular Task.

Rewrite your fluent methods to this form - i.e. it makes little sense for them to be extension methods:

        public static async Task<ResultType> Transform(SourceType original)
        {
            // some async work 
            var transformed = await DoSomething(original)
            return transformed;
        }

Provide these generic extension methods (pretty much the same as @Gennadii Saltyshchak's PipeSync methods, but I find the "Then" moniker much more succinct):

        public static async Task<T2> Then<T1, T2>(this T1 first, Func<T1, Task<T2>> second)
        {
            return await second(first).ConfigureAwait(false);
        }

        public static async Task<T2> Then<T1, T2>(this Task<T1> first, Func<T1, Task<T2>> second)
        {
            return await second(await first.ConfigureAwait(false)).ConfigureAwait(false);
        }

        public static async Task<T2> Then<T1, T2>(this Task<T1> first, Func<T1, T2> second)
        {
            return second(await first.ConfigureAwait(false));
        }

        public static Task<T2> Then<T1, T2>(this T1 first, Func<T1, T2> second)
        {
            return Task.FromResult(second(first));
        }

You can then construct a fluent chain like this:

        var processed = await Transform1(source)
            .Then(Transform1)
            .Then(Transform2)
            .Then(Transform3);

Thanks to the Then() overloads, this works with any permutation of async/sync methods.

If e.g. Transform2 takes arguments, you need to expand to a lambda:

        var processed = await Transform1(source)
            .Then(Transform1)
            .Then(x => Transform2(x, arg1, arg2))
            .Then(Transform3);

I think this is as close to a fluent async chain as you can get with the current language!

Combinations of async/sync should be optimized with ValueTask where possible. An exercise for the reader! :-)

Another option is to implement the basic LINQ operators to allow LINQ syntax. Then you can do this:

MyEntity Xx = await
    from f in FirstStepAsync()
    from e in f.SecondStepAsync()
    select e;

The code you need is this:

public static class Ex
{
    public static Task<TResult> SelectMany<TSource, TResult>(this Task<TSource> source, Func<TSource, Task<TResult>> collectionSelector)
        => source.ContinueWith(t => collectionSelector(t.Result)).Unwrap();

    public static Task<TResult> SelectMany<TSource, TCollection, TResult>(this Task<TSource> source, Func<TSource, Task<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)
        => source.ContinueWith(t =>
        {
            Task<TCollection> ct = collectionSelector(t.Result);
            return ct.ContinueWith(_ => resultSelector(t.Result, ct.Result));
        }).Unwrap();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!