'while'在异步计算表达式中,条件是异步的

Jar*_*ore 10 f# asynchronous sqldatareader sqlclient

我正在玩F#中使用SqlClient而且我在使用时遇到了困难SqlDataReader.ReadAsync.我正在尝试做F#等价的

while (await reader.ReadAsync) { ... }

在F#中做到这一点的最佳方法是什么?以下是我的完整计划.它有效,但我想知道是否有更好的方法来做到这一点.

open System
open System.Data.SqlClient
open System.Threading.Tasks

let connectionString = "Server=.;Integrated Security=SSPI"

module Async =
    let AwaitVoidTask : (Task -> Async<unit>) =
        Async.AwaitIAsyncResult >> Async.Ignore

    // QUESTION: Is this idiomatic F#? Is there a more generally-used way of doing this?
    let rec While (predicateFn : unit -> Async<bool>) (action : unit -> unit) : Async<unit> = 
        async {
            let! b = predicateFn()
            match b with
                | true -> action(); do! While predicateFn action
                | false -> ()
        }

[<EntryPoint>]
let main argv = 
    let work = async {
        // Open connection
        use conn = new SqlConnection(connectionString)
        do! conn.OpenAsync() |> Async.AwaitVoidTask

        // Execute command
        use cmd = conn.CreateCommand()
        cmd.CommandText <- "select name from sys.databases"
        let! reader = cmd.ExecuteReaderAsync() |> Async.AwaitTask

        // Consume reader

        // I want a convenient 'while' loop like this...
        //while reader.ReadAsync() |> Async.AwaitTask do // Error: This expression was expected to have type bool but here has type Async<bool>
        //    reader.GetValue 0 |> string |> printfn "%s"
        // Instead I used the 'Async.While' method that I defined above.

        let ConsumeReader = Async.While (fun () -> reader.ReadAsync() |> Async.AwaitTask)
        do! ConsumeReader (fun () -> reader.GetValue 0 |> string |> printfn "%s")
    }
    work |> Async.RunSynchronously
    0 // return an integer exit code
Run Code Online (Sandbox Code Playgroud)

Tom*_*cek 10

您的代码中存在一个问题,即您正在使用递归调用
do! While predicateFn action.这是一个问题,因为它不会变成尾调用,因此最终可能会导致内存泄漏.正确的方法是使用return!而不是do!.

除此之外,您的代码运行良好.但您实际上可以扩展async计算构建器以允许您使用普通while关键字.为此,您需要稍微不同的版本While:

let rec While (predicateFn : unit -> Async<bool>) (action : Async<unit>) : Async<unit> = 
    async {
        let! b = predicateFn()
        if b then
            do! action
            return! While predicateFn action
    }

type AsyncBuilder with
    member x.While(cond, body) = Async.While cond body
Run Code Online (Sandbox Code Playgroud)

这里,正文也是异步的,它不是一个函数.然后我们While向计算构建器添加一个方法(所以我们添加另一个重载作为扩展方法).有了这个,你实际上可以写:

 while Async.AwaitTask(reader.ReadAsync()) do // This is async!
     do! Async.Sleep(1000)   // The body is asynchronous too
     reader.GetValue 0 |> string |> printfn "%s"
Run Code Online (Sandbox Code Playgroud)