【发布时间】: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