F#:第一个事件只执行一次操作,而没有可变性/锁定? [英] F#: only do one action once for the first event, without mutability/locking?

查看:52
本文介绍了F#:第一个事件只执行一次操作,而没有可变性/锁定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可以下载文件,并在控制台中告诉我文件的大小:

I have this code that downloads a file and tells me in the console how big is the file:

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()

有没有办法做到这一点,但是既不使用锁定变量也不使用可变变量?

Is there a way to do the same, but using neither locking nor mutable vars?

推荐答案

以下是使用Reactive Extensions的一种方法:

Here is one way using the Reactive Extensions:

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))

这篇关于F#:第一个事件只执行一次操作,而没有可变性/锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆