Concurrent and parallel programming in F#
let fetchUrlAsync url =
async {
let! html = HttpClient.GetStringAsync(url)
|> Async.AwaitTask
return html.Length
}
let lengths =
["http://example.com"; "http://fsharp.org"]
|> List.map fetchUrlAsync
|> Async.Parallel
|> Async.RunSynchronously
let computeTask() = task {
let! result1 = Task.Run(fun () -> 2 + 2)
let! result2 = Task.Run(fun () -> 3 * 3)
return result1 + result2
}
let finalResult = computeTask().Result
type Message =
| Increment of int
| GetCount of AsyncReplyChannel
let counter = MailboxProcessor.Start(fun inbox ->
let rec loop count = async {
let! msg = inbox.Receive()
match msg with
| Increment n -> return! loop (count + n)
| GetCount reply ->
reply.Reply(count)
return! loop count
}
loop 0)