某些API(如WebClient)使用基于事件的异步模式。虽然这看起来很简单,并且可能在松散耦合的应用程序(例如,UI中的BackgroundWorker)中运行良好,但它并不能很好地链接在一起。

例如,这是一个多线程程序,因此异步工作不会阻塞。 (想象一下,这是在一个服务器应用程序中,并且调用了数百次 - 你不想阻止你的ThreadPool线程。)我们得到3个局部变量(“state”),然后进行2次异步调用,结果是第一个进入第二个请求(所以他们不能并行)。国家也可以变异(容易添加)。

使用WebClient,事情最终会像下面一样(或者你最终会创建一堆对象来像闭包一样):

using System;
using System.Net;

class Program
{
    static void onEx(Exception ex) {
        Console.WriteLine(ex.ToString());
    }

    static void Main() {
        var url1 = new Uri(Console.ReadLine());
        var url2 = new Uri(Console.ReadLine());
        var someData = Console.ReadLine();

        var webThingy = new WebClient();
        DownloadDataCompletedEventHandler first = null;
        webThingy.DownloadDataCompleted += first = (o, res1) => {
            if (res1.Error != null) {
                onEx(res1.Error);
                return;
            }
            webThingy.DownloadDataCompleted -= first;
            webThingy.DownloadDataCompleted += (o2, res2) => {
                if (res2.Error != null) {
                    onEx(res2.Error);
                    return;
                }
                try {
                    Console.WriteLine(someData + res2.Result);
                } catch (Exception ex) { onEx(ex); }
            };
            try {
                webThingy.DownloadDataAsync(new Uri(url2.ToString() + "?data=" + res1.Result));
            } catch (Exception ex) { onEx(ex); }
        };
        try {
            webThingy.DownloadDataAsync(url1);
        } catch (Exception ex) { onEx(ex); }

        Console.WriteLine("Keeping process alive");
        Console.ReadLine();
    }

}

是否有一种通用的方法来重构这种基于事件的异步模式? (即,不必为每个这样的API编写详细的扩展方法?)BeginXXX和EndXXX使它变得简单,但这种事件方式似乎没有任何提供。

有帮助吗?

解决方案

您可能需要查看 F# F#可以使用«工作流程»自动为您编码。特征。 {code> F#的'08 PDC演示文稿使用名为 async 的标准库工作流来处理异步Web请求,该工作流处理 BeginXXX / EndXXX 模式,但您可以毫不费力地为事件模式编写工作流程,或者找到一个罐装模型。 F#适用于C#。

其他提示

过去我使用迭代器方法实现了这个:每次你想要另一个URL请求时,你都使用“yield return”和“yield return”。将控制权传递回主程序。请求完成后,主程序将回调您的迭代器以执行下一项工作。

您正在有效地使用C#编译器为您编写状态机。优点是你可以在迭代器方法中编写看起来很正常的C#代码来驱动整个事情。

using System;
using System.Collections.Generic;
using System.Net;

class Program
{
    static void onEx(Exception ex) {
        Console.WriteLine(ex.ToString());
    }

    static IEnumerable<Uri> Downloader(Func<DownloadDataCompletedEventArgs> getLastResult) {
        Uri url1 = new Uri(Console.ReadLine());
        Uri url2 = new Uri(Console.ReadLine());
        string someData = Console.ReadLine();
        yield return url1;

        DownloadDataCompletedEventArgs res1 = getLastResult();
        yield return new Uri(url2.ToString() + "?data=" + res1.Result);

        DownloadDataCompletedEventArgs res2 = getLastResult();
        Console.WriteLine(someData + res2.Result);
    }

    static void StartNextRequest(WebClient webThingy, IEnumerator<Uri> enumerator) {
        if (enumerator.MoveNext()) {
            Uri uri = enumerator.Current;

            try {
                Console.WriteLine("Requesting {0}", uri);
                webThingy.DownloadDataAsync(uri);
            } catch (Exception ex) { onEx(ex); }
        }
        else
            Console.WriteLine("Finished");
    }

    static void Main() {
        DownloadDataCompletedEventArgs lastResult = null;
        Func<DownloadDataCompletedEventArgs> getLastResult = delegate { return lastResult; };
        IEnumerable<Uri> enumerable = Downloader(getLastResult);
        using (IEnumerator<Uri> enumerator = enumerable.GetEnumerator())
        {
            WebClient webThingy = new WebClient();
            webThingy.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs e) {
                if (e.Error == null) {
                    lastResult = e;
                    StartNextRequest(webThingy, enumerator);
                }
                else
                    onEx(e.Error);
            };

            StartNextRequest(webThingy, enumerator);
        }

        Console.WriteLine("Keeping process alive");
        Console.ReadLine();
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top