Skip to content

Instantly share code, notes, and snippets.

@isaacabraham
Created October 9, 2013 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaacabraham/6909518 to your computer and use it in GitHub Desktop.
Save isaacabraham/6909518 to your computer and use it in GitHub Desktop.
Pretty much the same sample as asyncsample.cs except in F#...
open System
open System.Diagnostics
open System.Net
open System.Threading
let consolePrinter =
MailboxProcessor.Start(fun agent ->
async {
while true do
let! message = agent.Receive()
let text, url, thread = message
printfn "%s %s on thread %d" text url thread
})
let urlList =
[| "http://www.tottenhamhotspur.com"; "http://cockneycoder.com"; "http://www.bbc.co.uk";
"http://www.bbc.co.uk/sport/0/football/"; "http://www.sky.com" |]
let getThreadId() = Thread.CurrentThread.ManagedThreadId
let timeDownload code args =
let stopwatch = Stopwatch.StartNew()
code args
stopwatch.Stop()
printfn "Done in %dms." stopwatch.ElapsedMilliseconds
let downloadUrl collectionOp urls =
urls |> collectionOp (fun url ->
consolePrinter.Post("Downloading", url, getThreadId())
use wc = new WebClient()
wc.DownloadString(Uri(url)) |> ignore
consolePrinter.Post("Downloaded", url, getThreadId()))
let sequentialDownload = downloadUrl Array.iter
let parallelDownload = downloadUrl Array.Parallel.iter
let asyncDownload urls =
urls
|> Array.map (fun url ->
async {
consolePrinter.Post("Downloading", url, getThreadId())
use wc = new WebClient()
let! work = wc.AsyncDownloadString(Uri(url))
consolePrinter.Post("Downloaded", url, getThreadId())
})
|> Async.Parallel
|> Async.RunSynchronously
|> ignore
printfn "Sequential"
printfn ""
(timeDownload sequentialDownload) urlList
printfn "Parallel"
printfn ""
(timeDownload parallelDownload) urlList
printfn "Async"
printfn ""
(timeDownload asyncDownload) urlList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment