我有这段代码,它下载了一个文件,并在控制台中告诉我文件有多大:
use webClient = new WebClient()
let lockObj = new Object()
let mutable firstProgressEvent = true
let onProgress (progressEventArgs: DownloadProgressChangedEventArgs) =
lock lockObj (fun _->
if (firstProgressEvent) then
let totalSizeInMB = progressEventArgs.TotalBytesToReceive / 1000000L
Console.WriteLine ("Starting download of {0}MB...", totalSizeInMB)
firstProgressEvent <- false
)
webClient.DownloadProgressChanged.Subscribe onProgress |> ignore
let task = webClient.DownloadFileTaskAsync (uri, Path.GetFileName(uri.LocalPath))
task.Wait()
有没有办法做同样的事情,但既不使用锁定也不使用可变变量?
以下是使用反应式扩展的一种方法:
open System.Net
open FSharp.Control
let webClient = new WebClient()
let disposable =
Observable.take 1 webClient.DownloadProgressChanged
|> Observable.subscribe (fun progress -> printfn "%A" (progress.TotalBytesToReceive))