macos – 为什么我不使用这个F#代码在OSX上输出,但我在Windows上输出

我正在尝试使用Visual Studio代码中的FSI和ionide插件在我的macbook pro上执行以下F#脚本代码.

#r "packages/Newtonsoft.Json.9.0.1/lib/net40/Newtonsoft.Json.dll"
#r "System.Net.Http"

open System
open System.Net.Http
open Newtonsoft.Json

let client = new HttpClient()

type AlbumInfo = { userId:int; id:int; title:string }

let url = "https://jsonplaceholder.typicode.com/albums/1"

async {
    let! res = Async.AwaitTask <| client.GetAsync(url)
    let! content = Async.AwaitTask <| res.Content.ReadAsStringAsync()
    let  x = JsonConvert.DeserializeObject<AlbumInfo>(content)

    printfn "%s" x.title
} |> Async.Start

printfn "Please wait..."

但我没有得到任何输出请等待….但是,当我把https://jsonplaceholder.typicode.com/albums/1放入浏览器时,我得到了预期的Json响应.所以我知道到达API是没有问题的.

此外,当我在Windows 10 PC上的Visual Studio 2013中运行相同的代码时.代码产生预期的结果.即请等待……以及专辑的标题.

任何想法为什么它在我的macbook上无法正常工作?

最佳答案 在Visual Studio中,有一个托管FSI的进程,并保持异步计算的线程(池)保持活动状态.在命令行或VS代码的FSI中,FSI将在主线程完成写入后立即终止请等待…(通常是在线程池上开始计算之前).

如果要观察异步计算的副作用,则必须等待其结果(在此示例单元中):

let computation = async {
    printfn "Starting async"
    let! res = Async.AwaitTask <| client.GetAsync(url)
    let! content = Async.AwaitTask <| res.Content.ReadAsStringAsync()
    let x = JsonConvert.DeserializeObject<AlbumInfo>(content)
    printfn "Downloaded %s" x.title
}

async {
    let! started = computation |> Async.StartChild
    let! _ = Async.Sleep 1 // only here to get interleaved ouput
    printfn "Please wait..."
    let! res = started
    printfn "Got result %A" res
} |> Async.RunSynchronously

可能打印:

Starting async
Please wait…
Downloaded quidem molestiae enim
Got result <null>

点赞