Understanding F# Asynchronous Programming
Posted
by Yin Zhu
on Stack Overflow
See other posts from Stack Overflow
or by Yin Zhu
Published on 2010-03-15T02:05:30Z
Indexed on
2010/03/15
2:09 UTC
Read the original article
Hit count: 330
F#
|asynchronous
I kind of know the syntax of asynchronous programming in F#. E.g.
let downloadUrl(url:string) = async {
let req = HttpWebRequest.Create(url)
// Run operation asynchronously
let! resp = req.AsyncGetResponse()
let stream = resp.GetResponseStream()
// Dispose 'StreamReader' when completed
use reader = new StreamReader(stream)
// Run asynchronously and then return the result
return! reader.AsyncReadToEnd() }
In F# expert book (and many other sources), they say like
let! var = expr simply means "perform the asynchronous operation expr and bind the result to var when the operation completes. Then continue by executing the rest of the computation body"
I also know that a new thread is created when performing async operation. My original understanding was that there are two parallel threads after the async operation, one doing I/O and one continuing to execute the async body at the same time.
But in this example, I am confused at
let! resp = req.AsyncGetResponse()
let stream = resp.GetResponseStream()
What happens if resp
has not started yet and the thread in the async body wants to GetResponseStream
? Is this a possible error?
So maybe my original understanding was wrong. The quoted sentences in the F# expert book actually means that "creating a new thread, hang the current thread up, when the new thread finishes, wake up the body thread and continue", but in this case I don't see we could save any time.
In the original understanding, the time is saved when there are several independent IO operations in one async block so that they could be done at the same time without intervention with each other. But here, if I don't get the response, I cannot create the stream; only I have stream, I can start reading the stream. Where's the time gained?
© Stack Overflow or respective owner