ZetCode

F# async and tasks

last modified December 3, 2026

In this article we write asynchronous code in F# with async and task expressions.

Asynchronous code waits for something, such as a timer, a file or a network reply, without blocking a thread. F# has two computation expressions for it. async { } builds an Async<'T>, a description of work that runs when we start it. task { } builds a .NET Task<'T>, which starts at once and is what most .NET libraries return. Both use let! and do! to wait for a result; how such builders work is explained in F# computation expressions.

A first async

An async block may wait with do! and return a value with return. Async.RunSynchronously runs it and waits for the result.

first.fsx
let greet = async {
    printfn "starting"
    do! Async.Sleep 500
    printfn "Hello there!"
    return 42
}

let n = Async.RunSynchronously greet
printfn "result: %d" n

The program waits half a second between the two messages.

do! Async.Sleep 500

Async.Sleep returns an Async<unit>. do! waits for it to finish. Unlike Thread.Sleep, it does not block a thread while waiting; the thread is free for other work.

let n = Async.RunSynchronously greet

The type of greet is Async<int>. Async.RunSynchronously runs it and blocks until it returns the int. A script needs one such call at the end; in larger programs the rest of the code stays asynchronous.

λ dotnet fsi first.fsx
starting
Hello there!
result: 42

Async values are cold

Defining an async value does not run it. The value is a recipe that runs each time it is started.

cold.fsx
let job = async {
    printfn "job runs"
    return 1
}

printfn "job defined"
let a = Async.RunSynchronously job
let b = Async.RunSynchronously job
printfn "a + b = %d" (a + b)

The job is defined first and started twice.

printfn "job defined"

The output shows that nothing in the block ran when job was bound. Each Async.RunSynchronously call runs the whole block again, so the message appears twice.

λ dotnet fsi cold.fsx
job defined
job runs
job runs
a + b = 2

Waiting for results with let!

let! starts another async computation, waits for it and binds its result. Several let! lines run one after another. We simulate downloads with Async.Sleep and measure the time with a Stopwatch.

sequential.fsx
open System.Diagnostics

let download (name: string) (ms: int) = async {
    do! Async.Sleep ms
    printfn "%s done" name
    return name.Length * 100
}

let both = async {
    let! a = download "index.html" 400
    let! b = download "style.css" 300
    return a + b
}

let sw = Stopwatch.StartNew()
let size = Async.RunSynchronously both
printfn "%d bytes in %.1f s" size sw.Elapsed.TotalSeconds

The download function returns an async computation that pretends to fetch a file.

let! a = download "index.html" 400
let! b = download "style.css" 300

The second download starts only after the first one has finished, so the total time is the sum of the two delays. Measured times may differ by a few hundredths of a second between runs.

λ dotnet fsi sequential.fsx
index.html done
style.css done
1900 bytes in 0.7 s

Running in parallel

Async.Parallel turns a list of async computations into one computation that runs them all at the same time and returns their results in an array. We move download into a file so the following examples can load it.

downloads.fsx
let download (name: string) (ms: int) = async {
    do! Async.Sleep ms
    printfn "%s done" name
    return name.Length * 100
}

Four downloads with different delays are started together.

parallel.fsx
#load "downloads.fsx"
open System.Diagnostics
open Downloads

let files = [ "index.html", 400; "style.css", 300; "logo.png", 600; "app.js", 500 ]

let sw = Stopwatch.StartNew()

let sizes =
    files
    |> List.map (fun (name, ms) -> download name ms)
    |> Async.Parallel
    |> Async.RunSynchronously

printfn "%A" sizes
printfn "total %d bytes in %.1f s" (Array.sum sizes) sw.Elapsed.TotalSeconds

List.map creates four async computations; none of them runs yet.

|> Async.Parallel

Async.Parallel starts all of them on the thread pool. They finish in the order of their delays, but the array keeps the order of the input list. The total time is that of the longest download, not the sum.

λ dotnet fsi parallel.fsx
style.css done
index.html done
app.js done
logo.png done
[|1000; 900; 800; 600|]
total 3300 bytes in 0.6 s

Limiting parallelism

Starting everything at once is not always wise; a server may limit the number of connections. Async.Parallel takes an optional maximum, and Async.Sequential runs the computations one at a time but still collects the results in an array.

throttle.fsx
open System.Diagnostics

let job (i: int) = async {
    do! Async.Sleep 300
    return i * 100
}

let jobs () = [ for i in 1 .. 6 -> job i ]

let measure label (work: Async<int[]>) =
    let sw = Stopwatch.StartNew()
    let sizes = Async.RunSynchronously work
    printfn "%s: %d jobs in %.1f s" label sizes.Length sw.Elapsed.TotalSeconds

measure "two at a time" (Async.Parallel(jobs (), maxDegreeOfParallelism = 2))
measure "one at a time" (Async.Sequential(jobs ()))

Six jobs of 300 ms each are run in two ways. The jobs print nothing: two jobs that finish at the same moment could mix their printfn output, because printfn writes a line in several pieces.

Async.Parallel(jobs (), maxDegreeOfParallelism = 2)

With at most two running at once, the six jobs take three rounds, about 0.9 s. Run one at a time they take about 1.8 s.

λ dotnet fsi throttle.fsx
two at a time: 6 jobs in 0.9 s
one at a time: 6 jobs in 1.8 s

Errors

An exception raised inside an async computation is passed on to the code that waits for it. We can handle it with try and with inside an async block, or turn it into a value with Async.Catch.

errors.fsx
let root n = async {
    do! Async.Sleep 100
    if n < 0 then failwith $"negative input {n}"
    return sqrt (float n)
}

let safeRoot n = async {
    try
        let! r = root n
        return Ok r
    with ex ->
        return Error ex.Message
}

printfn "%A" (Async.RunSynchronously (safeRoot 16))
printfn "%A" (Async.RunSynchronously (safeRoot -4))

let all = [ root 4; root -1; root 9 ] |> Async.Parallel |> Async.Catch

match Async.RunSynchronously all with
| Choice1Of2 values -> printfn "values %A" values
| Choice2Of2 ex -> printfn "caught: %s" ex.Message

The root computation fails for negative numbers.

try
    let! r = root n
    return Ok r
with ex ->
    return Error ex.Message

A try ... with works in an async block as in ordinary code (see F# exceptions), and it also catches exceptions from computations awaited with let!.

let all = [ root 4; root -1; root 9 ] |> Async.Parallel |> Async.Catch

When one computation of Async.Parallel fails, the whole computation fails and the other results are lost. Async.Catch returns a Choice value: Choice1Of2 with the result or Choice2Of2 with the exception.

λ dotnet fsi errors.fsx
Ok 4.0
Error "negative input -4"
caught: negative input -1

Cancellation

A running async computation can be cancelled. A CancellationTokenSource creates a token that we pass when we start the computation; cancelling the source stops the computation at its next let! or do!.

cancel.fsx
open System
open System.Threading

let ticker = async {
    for i in 1 .. 10 do
        printfn "tick %d" i
        do! Async.Sleep 200
    printfn "all ticks done"
}

let cts = new CancellationTokenSource()
cts.CancelAfter 700

try
    Async.RunSynchronously(ticker, cancellationToken = cts.Token)
with :? OperationCanceledException ->
    printfn "ticker stopped"

The ticker would print ten ticks, 200 ms apart, but it is cancelled after 700 ms.

cts.CancelAfter 700

CancelAfter cancels the source after the given number of milliseconds; cts.Cancel() would cancel it at once. The token is checked by Async.Sleep and at every let! and do!, so the computation needs no code of its own to stop.

with :? OperationCanceledException ->

Async.RunSynchronously reports the cancellation by raising OperationCanceledException. The loop stops during the fourth sleep, so the last line of the block never runs.

λ dotnet fsi cancel.fsx
tick 1
tick 2
tick 3
tick 4
ticker stopped

Tasks

A task { } expression creates a .NET Task<'T>. Unlike an async, a task is hot: it starts running as soon as it is created.

tasks.fsx
open System.Threading.Tasks

let work (name: string) = task {
    printfn "%s started" name
    do! Task.Delay 300
    printfn "%s finished" name
    return name.Length
}

let t = work "report"
printfn "task created"
printfn "result %d" t.Result

The work function returns a task that waits 300 ms.

let t = work "report"
printfn "task created"

The started line comes before task created: the task body runs right away until its first do!. Calling the function again would start a second task; a task is a running operation, not a recipe.

printfn "result %d" t.Result

The Result property blocks until the task finishes. Like Async.RunSynchronously, it belongs at the top of a program, not inside other asynchronous code.

λ dotnet fsi tasks.fsx
report started
task created
report finished
result 6

Waiting for several tasks

Since tasks start at once, starting several of them already runs them in parallel. Task.WhenAll waits for all of them and returns their results in an array.

when_all.fsx
open System.Diagnostics
open System.Threading.Tasks

let fetch (name: string) (ms: int) = task {
    do! Task.Delay ms
    printfn "%s done" name
    return name.Length * 100
}

let site = task {
    let! sizes = Task.WhenAll [ fetch "index.html" 400; fetch "style.css" 300 ]
    let! extra = fetch "logo.png" 200
    return Array.sum sizes + extra
}

let sw = Stopwatch.StartNew()
printfn "%d bytes in %.1f s" site.Result sw.Elapsed.TotalSeconds

The program fetches two files together and a third one after them.

let! sizes = Task.WhenAll [ fetch "index.html" 400; fetch "style.css" 300 ]

The list creates two running tasks and Task.WhenAll waits for both, which takes 0.4 s. The third let! starts only afterwards and adds 0.2 s.

λ dotnet fsi when_all.fsx
style.css done
index.html done
logo.png done
2700 bytes in 0.6 s

An async cannot wait for a task

.NET methods return tasks, while many F# functions return async values. An async block cannot wait for a task directly.

mismatch.fsx
open System.Threading.Tasks

let fetch (n: int) = task {
    do! Task.Delay 100
    return n * 2
}

let doubled = async {
    let! x = fetch 21
    return x
}

let! in an async block expects an Async value and the compiler rejects the task.

λ dotnet fsi mismatch.fsx
mismatch.fsx(9,14): error FS0001: This expression was expected to have type
    'Async<'a>'
but here has type
    'Task<int>'

Converting between async and tasks

Async.AwaitTask converts a task into an async computation and Async.StartAsTask goes the other way. A task block, on the other hand, can wait for an async value with let! directly.

convert.fsx
open System.Threading.Tasks

let fetch (n: int) = task {
    do! Task.Delay 100
    return n * 2
}

let doubled = async {
    let! x = fetch 21 |> Async.AwaitTask
    return x
}

let asTask: Task<int> = Async.StartAsTask doubled
printfn "from async: %d" asTask.Result

let combined = task {
    let! a = doubled
    let! b = fetch 5
    return a + b
}

printfn "combined: %d" combined.Result

The doubled computation waits for a task, and the combined task waits for both an async value and a task.

let! x = fetch 21 |> Async.AwaitTask

Async.AwaitTask is the fix for the error above. Async.StartAsTask starts doubled and returns a task, which is useful when a .NET API expects one.

λ dotnet fsi convert.fsx
from async: 42
combined: 52

Asynchronous file I/O

The File class has asynchronous versions of the methods shown in F# file I/O. Their names end in Async and they return tasks.

file_async.fsx
open System.IO
open System.Threading.Tasks

let path = "notes.txt"

let run = task {
    do! File.WriteAllTextAsync(path, "buy milk\ncall Martin\n")
    do! File.AppendAllLinesAsync(path, [ "water the plants" ])
    let! lines = File.ReadAllLinesAsync path
    for line in lines do
        printfn "- %s" line
    return lines.Length
}

printfn "%d notes" run.Result

The task writes a file, appends a line, and reads the file back.

do! File.WriteAllTextAsync(path, "buy milk\ncall Martin\n")

WriteAllTextAsync returns a plain Task with no result, which do! waits for. While the operating system writes the file, the thread can do other work.

for line in lines do
    printfn "- %s" line

Ordinary loops and printfn calls may appear in a task block between the waiting steps.

λ dotnet fsi file_async.fsx
- buy milk
- call Martin
- water the plants
3 notes

Counting words in files

The last program reads several text files at the same time and counts the words in each. These are the three input files.

spring.txt
The snow is melting on the hills.
Birds return to the old garden.
summer.txt
Long days and warm nights.
autumn.txt
Leaves fall from the trees.
The wind is cold and the rain is long.
Apples are ripe in the orchard.

Each file is read by its own task, and a missing file becomes an error instead of stopping the program.

wordcount.fsx
open System
open System.IO
open System.Threading.Tasks

let countWords (path: string) = task {
    try
        let! text = File.ReadAllTextAsync path
        let words = text.Split([| ' '; '\n' |], StringSplitOptions.RemoveEmptyEntries)
        return path, Ok words.Length
    with :? FileNotFoundException ->
        return path, Error "file not found"
}

let report (paths: string list) = task {
    let! counts = paths |> List.map countWords |> Task.WhenAll
    for path, count in counts do
        match count with
        | Ok n -> printfn "%-11s %3d words" path n
        | Error e -> printfn "%-11s %s" path e
    let total = counts |> Array.sumBy (fun (_, c) -> Result.defaultValue 0 c)
    printfn "%-11s %3d words" "total" total
}

let t = report [ "spring.txt"; "summer.txt"; "autumn.txt"; "winter.txt" ]
t.Wait()

The countWords function returns a task with the file name and a Result.

with :? FileNotFoundException ->
    return path, Error "file not found"

An exception from an awaited task is caught by try ... with in the task block, just as in async. Turning it into an Error means one missing file does not make Task.WhenAll fail.

let! counts = paths |> List.map countWords |> Task.WhenAll

List.map starts one task per file and Task.WhenAll waits for all of them. The results come back in the order of the input list, whichever file is read first.

t.Wait()

report returns a Task without a result, so we wait with Wait instead of reading Result.

λ dotnet fsi wordcount.fsx
spring.txt   13 words
summer.txt    5 words
autumn.txt   20 words
winter.txt  file not found
total        38 words

Source

F# language reference: Async expressions

F# language reference: Task expressions

F# documentation: Async programming in F#

In this article we have written asynchronous code with async and task expressions. We have run async computations, seen that they are cold while tasks are hot, waited for results with let! and do!, run work in parallel with Async.Parallel and Task.WhenAll, handled errors and cancellation, converted between the two types, and read files asynchronously. Builders such as async are explained in F# computation expressions, and the file methods in F# file I/O.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all F# tutorials.