目前我正在使用此代码来获取文件:
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:removeHandler
是Action
(那是什么)?
这些重载非常棘手,我每次都要查看它们.我已经包含了一些示例订阅代码来帮助您入门:
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的建议,可以在功能样式中执行所有这些代码,这也可以处理所有IDisposable
s的清理.但是,我发现它不具有可读性,因此不推荐它:
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