【问题标题】:Why Async.Sequential doesn't work as expected (but works in FSI)?为什么 Async.Sequential 不能按预期工作(但在 FSI 中工作)?
【发布时间】:2020-03-17 05:42:16
【问题描述】:
open System
open System.Net

let fetchUrlAsync url = 
    async {
        Console.WriteLine(sprintf "Fetch <%s>" url)
        let req = WebRequest.Create(Uri(url)) 
        use! resp = req.AsyncGetResponse()   
        use stream = resp.GetResponseStream() 
        use reader = new IO.StreamReader(stream) 
        let html = reader.ReadToEnd() 
        Console.WriteLine(sprintf "finished downloading %s. Length = %i" url html.Length)
    }

[<EntryPoint>]
let main argv =
    ["http://bing.com"; "http://ya.ru"; "http://google.com"]
    |> List.map fetchUrlAsync
    |> Async.Sequential
    |> Async.Ignore
    |> Async.RunSynchronously


输出:

Fetch <http://bing.com>
Fetch <http://ya.ru>
Fetch <http://google.com>
finished downloading http://google.com. Length = 50592
finished downloading http://ya.ru. Length = 20541
finished downloading http://bing.com. Length = 81386

我不期望这样的输出(但也许我的期望错了)。但是如果我在 F# 交互中运行相同的代码,输出是(如我所料):

Fetch <http://bing.com>
finished downloading http://bing.com. Length = 81386
Fetch <http://ya.ru>
finished downloading http://ya.ru. Length = 20544
Fetch <http://google.com>
finished downloading http://google.com. Length = 50561

为什么从 Rider(控制台应用程序)和 F# Interactive 运行时代码的行为不同?如果第一个输出是正确的,那么 Async.Sequential 和 Async.Parallel 有什么区别?如果第一个输出不正确,那么如何解决?

【问题讨论】:

    标签: asynchronous f# f#-interactive


    【解决方案1】:

    目前,Async.Sequential 只是实现为:

    static member Sequential computations = 
        Async.Parallel(computations, maxDegreeOfParallelism=1)
    

    虽然the RFC allows this,但预计这将按顺序运行。 一直是discovered to be a bug。而且一直是fixed by #7596

    该修复程序现在仅在 VS 上发布。但它不在主线FSharp.Core nuget 提要中。

    目前获得修复的唯一方法是通过 VS2019 16.4 FSI。

    这就是为什么您看到它在 FSI 中正常工作,但在您编译的应用程序中却没有。

    解决方案

    观看 #7956,等待发货。

    【讨论】:

    • 包 FSharp.Core 4.7.1 在 NuGet 上可用。问题似乎已解决。
    猜你喜欢
    • 2021-05-30
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多