如何设计流畅的异步操作? [英] How to Design Fluent Async Operations?

查看:66
本文介绍了如何设计流畅的异步操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

异步操作似乎不适用于我更喜欢​​编写代码的流利接口.异步如何与Fluent结合使用?

Async operations do not seem to play well with fluent interfaces which I prefer to code in. How can Asynchrony be combined with Fluent?

示例:我有两个方法先前返回了MyEntity,但是在更改为Async时效果不佳.在使它们异步之后,我必须await任务的结果,但是我必须为添加的每个步骤执行此操作:

Sample: I have two methods that previously returned a MyEntity but do not play well when change to Async. After I asyncfy them I have to await the result of the tasks, but I have to do that for each step added:

MyEntity Xx = await(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.

我为您编写了一个示例实现.异步工作将在调用任何DoX方法后立即开始.

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

这篇关于如何设计流畅的异步操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆