I have a problem with developing a simple application in F#, which just reads the length of the requested HTML page.
Seems to be that such an error would be similar for VB.NET/C# language too, when you develop the UI application.
But I'm rather new to F# and don't really imagine hot to fix such issue exactly in F#.
Source code in F#:
open System
open System.Net
open Microsoft.FSharp.Control.WebExtensions
open System.Windows.Forms
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) =
async {
try
let uri = new System.Uri(url)
let webClient = new WebClient()
let! html = webClient.AsyncDownloadString(uri)
text.Text <- String.Format("Read %d characters for %s", html.Length, name)
with
| ex -> printfn "%s" (ex.Message);
}
let runAll() =
urlList
|> Seq.map fetchAsync
|> Async.Parallel
|> Async.RunSynchronously
|> ignore
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)
Best Regards,
Thanks!
You must switch thread context to UI thread from
Async ThreadPool
prior to updatingtext.Text
property. See MSDN link for the F# Async-specific explanation.After modifying your snippet by capturing UI context with
placed right after your
let form = new Form()
statement and changingfetchAsync
definition toit works without any problems.
UPDATE: After discussing the debugger idiosyncrasy with a colleague, who emphasized the need of cleanly manipulating UI context, the following modification is agnostic now to the manner of run: