当前位置:  开发笔记 > 编程语言 > 正文

使用Rx下载文件(反应式编程)

如何解决《使用Rx下载文件(反应式编程)》经验,为你挑选了1个好方法。

目前我正在使用此代码来获取文件:

WebClient webClient = new WebClient();
webClient.DownloadProgressChanged += webClient_DownloadProgressChanged;
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_ProgressCompleted);

我一直在查看文档,以便弄清楚如何使用Rx转换此代码.

我开始创建一个Observable使用FromEvent以观察DownloadFileCompleted事件.

Observable.FromEvent(?, ?)

然而,我无法想象如何填补这些?.

有人能举个例子吗?

到目前为止,我已尝试过:

Observable.FromEvent(?1:addHandler, ?2:removeHandler).

然而,.NET是请求我,?1:addHandler?2:removeHandlerAction>(那是什么)?



1> Shlomo..:

这些重载非常棘手,我每次都要查看它们.我已经包含了一些示例订阅代码来帮助您入门:

WebClient webClient = new WebClient();
var progressChangedObservable = Observable.FromEventPattern(
    h => webClient.DownloadProgressChanged += h,
    h => webClient.DownloadProgressChanged -= h
);

var downloadCompletedObservable = Observable.FromEventPattern(
    h => webClient.DownloadFileCompleted += h,
    h => webClient.DownloadFileCompleted -= h
);

progressChangedObservable
    .Select(ep => ep.EventArgs)
    .Subscribe(dpcea =>  Console.WriteLine($"{dpcea.ProgressPercentage}% complete. {dpcea.BytesReceived} bytes received. {dpcea.TotalBytesToReceive} bytes to receive."));

downloadCompletedObservable
    .Select(ep => ep.EventArgs)
    .Subscribe(_ => Console.WriteLine("Download file complete."));

var dummyDownloadPath = @"C:\temp\temp.txt";
webClient.DownloadFileAsync(new Uri(@"http://google.com"), dummyDownloadPath);

编辑:

根据@Enigmativity的建议,可以在功能样式中执行所有这些代码,这也可以处理所有IDisposables的清理.但是,我发现它不具有可读性,因此不推荐它:

    Observable.Using(() => 
    {
        var webClient = new WebClient();
        webClient.Headers.Add("User-Agent: Other");
        return webClient;
    }, webClient =>
    Observable.Using(() => 
        Observable.FromEventPattern(
                h => webClient.DownloadProgressChanged += h,
                h => webClient.DownloadProgressChanged -= h
            )
            .Select(ep => ep.EventArgs)
            .Subscribe(dpcea => Console.WriteLine($"{dpcea.ProgressPercentage}% complete. {dpcea.BytesReceived} bytes received. {dpcea.TotalBytesToReceive} bytes to receive.")),
        sub1 => Observable.Using(() =>
            Observable.FromEventPattern(
                    h => webClient.DownloadFileCompleted += h,
                    h => webClient.DownloadFileCompleted -= h
                )
                .Select(ep => ep.EventArgs)
                .Subscribe(_ => Console.WriteLine("Download file complete.")),
            sub2 => webClient.DownloadFileTaskAsync(new Uri(@"http://google.com"), @"C:\temp\temp.txt").ToObservable()
        )
    )
)
    .Subscribe(_ => {} ); //Subscription required to trigger nested observables


我写了这本书,每次都要查阅它.然而,对于快速黑客,好的旧`Observable.Create`可以更容易使用.
推荐阅读
帆侮听我悄悄说星星
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有