Agent are mailbox and can run async block, similar to run a async block inside a function.
open System
open System.Net
open Microsoft.FSharp.Control.WebExtensions
open System.Diagnostics
open System.IO
let urlList= ["cnn" , "http://www.cnn.com"
"china", "http://www.china.com"
]
let fetch( url :string) =
let uri = new Uri(url)
let c = new WebClient()
let html =c.DownloadString(uri)
printfn "%s" html
let fetchAsync(n: string, url :string) =
async {
let uri = new Uri(url)
let c = new WebClient()
let! html =c.AsyncDownloadString(uri)
printfn "%s" html
}
let runAsync() =
urlList
|> Seq.map fetchAsync
|> Async.Parallel
|> Async.RunSynchronously
let runSync() =
"http://www.cnn.com"
|> fetch
let s= new StreamWriter("c:\working\1.txt",true)
s.AutoFlush <-true
let agent =
MailboxProcessor.Start( fun inbox ->
async { while true do
let! msg =inbox.Receive()
// fetch(msg)
s.WriteLine(DateTime.Now.ToString()+ " "+msg);
})
[]
let main arg =
runSync()
fetch("http://www.cnn.com")
runAsync() |> ignore
agent.Post("http://www.cnn.com")
agent.Post("http://www.china.com")
agent.Post("http://www.goolge.com")
agent.Post("http://www.fb.com")
let mutable b=true
let mutable n=1
Console.ReadLine() |> ignore
while b do
n<-n+1
if n>1000 then
b <-false
agent.Post(n.ToString())
Console.ReadLine() |> ignore
s.Close()
0
Sunday, June 22, 2014
F# Async through Agent= inbox as Queue
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment