Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท Async and Concurrency

Async Workflows

Learn F# async workflows: async { }, let! and do!, running with Async.RunSynchronously and Async.Start, parallel composition, error handling, cancellation and the difference from .NET tasks.

Programs spend much of their time waiting: for a web service, a file, a database. A thread that waits is a wasted thread, and a server with thousands of waiting threads is a slow server. F# has had a clean answer to this since 2007: the async workflow. You write code that looks sequential, and the compiler turns it into a state machine that releases the thread whenever it has to wait. C# later copied the idea as async/await.

Your first async block

FSHARP
let fetchNumber (n: int) =
    async {
        do! Async.Sleep 500          // wait without blocking a thread
        return n * 2
    }

let result = fetchNumber 21 |> Async.RunSynchronously
printfn "%d" result    // 42

async { ... } builds a description of work, not the work itself. Nothing runs until you start it, with Async.RunSynchronously (blocks the caller until done; good for a main or a script) or one of the start functions below. Inside the block:

  • let! runs another async and binds its result when it completes: let! x = fetchNumber 1.
  • do! runs an async that returns unit.
  • return produces the final value; return! returns the result of another async directly.
  • A plain let binds an ordinary value.
FSHARP
let compute =
    async {
        let! a = fetchNumber 1
        let! b = fetchNumber 2
        printfn "got %d and %d" a b
        return a + b
    }

Steps run one after the other, just like normal code, but no thread sits blocked during the Sleep.

C# C# stand-in: the same workflow with async/await

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Cold start versus hot start

An F# async is cold: calling fetchNumber 21 returns a recipe, and you can run the same recipe many times. A .NET Task is hot: it starts the moment you create it. This difference matters when you compose and retry work: a cold async can be re-run for a retry, while a task that failed stays failed.

Running asyncs

FSHARP
Async.RunSynchronously (fetchNumber 1)         // run and wait, returns the value
Async.Start (async { printfn "fire and forget" })   // run in the background, ignore result
let t = Async.StartAsTask (fetchNumber 1)      // run as a .NET Task<int>

Use RunSynchronously at the top of the program only. Inside other async code use let!, never RunSynchronously, or you block a thread and risk deadlock.

Parallel composition

Awaiting with let! is sequential. To run several asyncs at once, combine them with Async.Parallel:

FSHARP
let slow n = async {
    do! Async.Sleep 1000
    return n * n
}

let all =
    [ for i in 1 .. 5 -> slow i ]
    |> Async.Parallel          // Async<int[]>
    |> Async.RunSynchronously

printfn "%A" all               // [|1; 4; 9; 16; 25|]  after about one second, not five

Async.Parallel starts all of them, waits for all and returns the results in the original order. Cap concurrency with Async.Parallel(tasks, maxDegreeOfParallelism = 3) when you must not hit a service with hundreds of requests at once. The structure is a classic fork and join:

flowchart LR
    S["Async.Parallel"] --> A["slow 1"]
    S --> B["slow 2"]
    S --> C["slow 3"]
    A --> J["results array"]
    B --> J
    C --> J

Fork the work, wait for every branch, collect the results in order.

Related: Async.Sequential runs them one at a time, and Async.Choice returns the first one that produces Some.

C# C# stand-in: running many tasks at once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Errors

Exceptions thrown inside an async propagate to whoever runs it, and try ... with works inside the block:

FSHARP
let safeDivide a b =
    async {
        try
            return a / b
        with :? System.DivideByZeroException ->
            printfn "divide by zero"
            return 0
    }

To turn an exception into a value, wrap the async with Async.Catch; it returns Choice<'T, exn>:

FSHARP
let outcome = Async.Catch (safeDivide 1 0) |> Async.RunSynchronously
match outcome with
| Choice1Of2 v -> printfn "ok %d" v
| Choice2Of2 ex -> printfn "failed: %s" ex.Message

Cancellation

Every async runs with a cancellation token, and cancelling it stops the work at the next let! or do!:

FSHARP
let cts = new System.Threading.CancellationTokenSource()

let worker = async {
    while true do
        printfn "tick"
        do! Async.Sleep 200
}

Async.Start(worker, cts.Token)
System.Threading.Thread.Sleep 700
cts.Cancel()

Inside an async you can read the token with let! token = Async.CancellationToken and pass it to .NET APIs. Cancellation is cooperative: tight loops with no let!/do! inside are never interrupted.

Choosing async or task

F# also has a task { } workflow that builds .NET Tasks directly (the next lesson). Rule of thumb: use async for pure F# code, cancellation-heavy code and when you want cold, composable work; use task when you call .NET APIs that return Task, as with HTTP clients and EF Core. See Tasks and Parallel Code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does the body of an async { } block start running?

    Asyncs are cold: they are descriptions of work that run only when started.
  2. 2. What does let! do inside an async block?

    let! awaits another async; the thread is released while waiting.
  3. 3. How do you run five asyncs at the same time?

    let! is sequential; Async.Parallel starts all of them and returns an array of results in order.
  4. 4. Why should you not call Async.RunSynchronously inside async code?

    Inside async code use let! so the thread is released while waiting.

Summary

  • async { } builds cold, composable descriptions of non-blocking work.
  • let!, do!, return and return! are the building blocks; steps run in sequence.
  • Run with Async.RunSynchronously at the top, Async.Start for fire-and-forget, Async.StartAsTask for interop.
  • Async.Parallel runs asyncs concurrently and keeps result order.
  • Errors use try/with or Async.Catch; cancellation is cooperative via a token.

Next: Tasks and Parallel Code