【问题标题】:Is there a useful design pattern for chained asynchronous/event calls?链式异步/事件调用是否有有用的设计模式?
【发布时间】:2010-07-19 20:58:28
【问题描述】:

我目前不得不在 Silverlight 中集成许多 Web 服务调用,这些调用类似于下面的代码。在所有 3 个加载完成之前,不应进行任何用户交互。

// In my view, having standard delegate methods (non-anonymous) makes the 
// code below even messier.

// I've left out the EventArgs to shorten the example however
// I usually use these objects in the delegate method.
MyService1 service1 = new MyService1();
service1.GetAllUsersCompleted += delegate
{
    MyService2 service2 = new MyService2();
    service2.AnotherTaskCompleted += delegate
    {
        MyService3 service3 = new MyService3();
        service3.YetAnotherTaskCompleted += delegate
        {
            // etc.
        };
        service3.YetAnotherTask();
    };
    service2.AnotherTask();
};
service1.GetAllUsers();

基本上我希望调用是同步的,但是由于 Silverlight 中 Web 服务代理类的架构(一切都是事件驱动的),我不能这样做。

我的问题是,是否有更优雅的解决方案或可能以 .NET 为中心的设计模式,用于将我所拥有的东西从一个委托方法调用另一个方法、调用另一个方法重构为更易于管理的东西?

我对代码的最大问题之一是实际的方法调用是在委托中的大部分工作之后进行的。

【问题讨论】:

    标签: c# design-patterns delegates anonymous-methods


    【解决方案1】:

    好吧,我建议您首先利用 Silverlight 的异步特性,尽可能同时运行所有三个调用。

    您可以对任务“按顺序”执行此操作(尤其是任务延续),但您可能还想查看 Rx library,它旨在优雅地处理这种情况。

    另一个最终提示:不建议禁止用户交互。至少给他们取消操作的选项。

    【讨论】:

      【解决方案2】:

      我认为这是新任务(在 Parallel 库中)类尝试抽象的内容,但我可能错了 :)

      【讨论】:

        【解决方案3】:

        我在这里可能错了,但代表们还没有同步。您可以使用 BeginInvoke 方法使它们异步。这是同步和异步方法调用的一个很好的资源,并解释了一些模式等。http://support.microsoft.com/kb/315582

        文章的标题可能是How to call a Visual C# method asynchronously,但是有大约一半的同步方法调用的例子。

        【讨论】:

        • 问题是所有 Web 服务引用都是事件驱动的
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多