用于说明 F# 中的异步工作流的一个常见示例是并行检索多个网页。一个这样的例子在:http ://en.wikibooks.org/wiki/F_Sharp_Programming/Async_Workflows此处显示的代码以防链接将来更改:
open System.Text.RegularExpressions
open System.Net
let download url =
let webclient = new System.Net.WebClient()
webclient.DownloadString(url : string)
let extractLinks html = Regex.Matches(html, @"http://\S+")
let downloadAndExtractLinks url =
let links = (url |> download |> extractLinks)
url, links.Count
let urls =
[@"http://www.craigslist.com/";
@"http://www.msn.com/";
@"http://en.wikibooks.org/wiki/Main_Page";
@"http://www.wordpress.com/";
@"http://news.google.com/";]
let pmap f l =
seq { for a in l -> async { return f a } }
|> Async.Parallel
|> Async.Run
let testSynchronous() = List.map downloadAndExtractLinks urls
let testAsynchronous() = pmap downloadAndExtractLinks urls
let time msg f =
let stopwatch = System.Diagnostics.Stopwatch.StartNew()
let temp = f()
stopwatch.Stop()
printfn "(%f ms) %s: %A" stopwatch.Elapsed.TotalMilliseconds msg temp
let main() =
printfn "Start..."
time "Synchronous" testSynchronous
time "Asynchronous" testAsynchronous
printfn "Done."
main()
我想知道的是应该如何处理全局状态的变化,例如网络连接丢失?有没有一种优雅的方式来做到这一点?
可以在进行 Async.Parallel 调用之前检查网络的状态,但在执行期间状态可能会发生变化。假设一个人想要做的是暂停执行,直到网络再次可用而不是失败,有没有一种功能性的方法可以做到这一点?