Created
December 16, 2013 20:52
-
-
Save dmitry-a-morozov/7994192 to your computer and use it in GitHub Desktop.
WinForms + Async
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open System | |
open System.Net | |
open Microsoft.FSharp.Control.WebExtensions | |
open System.Windows.Forms | |
open System.Threading | |
let form = new Form() | |
let text = new Label() | |
let button = new Button() | |
let urlList = [ "Microsoft.com", "http://www.microsoft.com/" | |
"MSDN", "http://msdn.microsoft.com/" | |
"Bing", "http://www.bing.com" | |
] | |
let fetchAsync(name, url:string, ctx) = | |
async { | |
try | |
let uri = new System.Uri(url) | |
let webClient = new WebClient() | |
let! html = webClient.AsyncDownloadString(uri) | |
do! Async.SwitchToContext ctx | |
text.Text <- sprintf "Read %d characters for %s" html.Length name | |
with | |
| ex -> printfn "%s" (ex.Message); | |
} | |
let runAll() = | |
let ctx = SynchronizationContext.Current | |
urlList | |
|> Seq.map (fun(site, url) -> fetchAsync(site, url, ctx)) | |
|> Async.Parallel | |
|> Async.Ignore | |
|> Async.Start | |
form.Width <- 400 | |
form.Height <- 300 | |
form.Visible <- true | |
form.Text <- "Test download tool" | |
text.Width <- 200 | |
text.Height <- 50 | |
text.Top <- 0 | |
text.Left <- 0 | |
form.Controls.Add(text) | |
button.Text <- "click me" | |
button.Top <- text.Height | |
button.Left <- 0 | |
button.Click |> Event.add(fun sender -> runAll() |> ignore) | |
form.Controls.Add(button) | |
[<STAThread>] | |
do Application.Run(form) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment