我正在玩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
答案 0 :(得分:8)
您的代码中存在一个问题,即您正在使用
进行递归调用
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
这里,正文也是异步的,它不是一个函数。然后我们将一个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"
答案 1 :(得分:0)
我可能和你一样。如果你可以戒烟,你可以将它缩短为
let go = ref true
while !go do
let! more = reader.ReadAsync() |> Async.AwaitTask
go := more
reader.GetValue 0 |> string |> printfn "%s"