CarbonFlambe
CarbonFlambe

Reputation: 378

Why nest async computations?

Consider the following two ways of constructing an Async computation that calculates 1 + 2:

let c1 =
    async {
        let a = 1
        let b = 2
        return a + b }

let c2 =
    async {
        let a = 1
        let! b = async { return 2 }
        return a + b }

What is the practical difference between them? It seems to me that they do the same thing. Why, for example, would you ever need to use let! result = streamReader.ReadToEndAsync () rather than let result = streamReader.ReadToEnd ()? Isn't it the case that both lines are "blocking" when the computation is run?

Upvotes: 2

Views: 82

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

Your silly example with let! b = async { return 2 } is indeed not bringing anything new. It's indeed completely equivalent to let b = 2.

It is a different story, however, with ReadToEnd vs. ReadToEndAsync. While they can both be described as "blocking", they are blocking is quite different ways.

ReadToEnd is synchronous. When it's called on a thread, that thread stops and waits for it to complete. The thread is blocked. It's doing nothing, but it also can't be used to execute anything else.

ReadToEndAsync uses asynchronous I/O (also called "overlapped I/O" on Windows). This basically means that the thread stops at this point and calls the OS, saying "hey, please read this file for me and wake me up when you're done". The way it's implemented at a lower level differs depending on the OS, but generally you get some sort of callback when the call completes.

This is kind of important in high-availability high-concurrency systems, such as HTTP servers. But if you're just running a script locally on your computer under human supervision, then just use whatever is more convenient.

Interestingly, the sync version ReadToEnd does actually use async I/O under the hood as well, it's just wrapped in a sync-blocking wrapper to make it more convenient to use in simple cases.

Upvotes: 2

Related Questions