Events and asynchronous computations

ITT8060 Advanced Programming · Autumn 2026

Tallinn University of Technology

Full prose version with runnable examples: notes.html

ITT8060

Five words

Synchronous: the caller starts an operation and waits until it has finished.

Asynchronous: the caller starts an operation and carries on. The result is delivered later.

Concurrency: several computations are in progress during the same period of time.

Parallelism: several computations run at the same instant, on several processors.

Reactive: the program does not decide when things happen. It responds to events as they arrive.

ITT8060

Why should we care?

Scalability, throughput, responsiveness, ...

If you are used to synchronous programming, then you need to think differently.

Nondeterminism: the same program can do things in a different order on each run.

ITT8060

Events and callbacks

An event is a representation of something happening: a mouse click, a changed file, a timer running out.

We listen to an event by registering a callback: a function of type X -> unit.

A callback is a description of what to do when the event fires.

Recall continuations (Lecture 8).

ITT8060

An event is a value

An Event<'T> has two sides: Publish for the listeners, Trigger to fire it.

manual.Publish
|> Event.filter (fun n -> n % 2 = 0)
|> Event.add (fun n -> printfn "Even: %d" n)

manual.Trigger 2
manual.Trigger 3

Events can be filtered, mapped and merged like collections.

ITT8060

Pull and push

pull:  unit -> (unit -> 'a)     enumerable -- enumerator
push:  ('a -> unit) -> unit     observable -- observer

Pull (Lecture 12): we ask for the next element, exactly when we want it.

Push: we hand over a callback. The collection calls it when it has an element. We are not in control of when that is.

ITT8060

Observables

let strCount =
  words.Publish
  |> Observable.scan (fun acc _ -> acc + 1) 0
  |> Observable.filter (fun i -> i % 5 = 0)

let merged = Observable.merge evs strCount

The Observable module: filter, map, scan, merge, partition.

Nothing happens until somebody subscribes. Observable.subscribe returns an IDisposable; disposing it ends the subscription.

ITT8060

Blocking and non-blocking

A blocking call holds on to its thread until the result is there, even when all it does is wait.

A non-blocking call starts the operation and gives the thread back. The rest of the work is done when the result arrives.

Written by hand, non-blocking code is a chain of callbacks.

async { } lets us write it like ordinary code.

ITT8060
let timerTest =
  async {
    printfn "Starting ..."
    do! sleepAsync 1000.0
    //failwith "error"
    printfn "Finished."
  }

async { } describes a computation

let! and do! wait without holding a thread.

An Async<'T> is a description. Defining it runs nothing.

It runs when we start it:

Async.RunSynchronously timerTest

ITT8060

async and task

async { } gives an Async<'T>: a description. It runs when it is started, and every time it is started.

task { } gives a Task<'T>: it is already running when we get it (Lecture 11). .Result waits for it.

Use task with .NET libraries that work with tasks.

Async.AwaitTask brings a task into an async.

ITT8060

Starting and combining

Async.RunSynchronously : Async<'a> -> 'a
Async.Start            : Async<unit> -> unit
Async.Parallel         : seq<Async<'a>> -> Async<'a array>
Async.Catch            : Async<'a> -> Async<Choice<'a, exn>>
let squares =
  Async.Parallel [ for i in 1 .. 5 -> async { return i * i } ]
  |> Async.RunSynchronously

[|1; 4; 9; 16; 25|]: the results are in the order of the computations.

ITT8060

Agents

An agent is a loop that receives messages, one at a time (MailboxProcessor).

Its state is the argument of the loop. No other code can touch it.

Other code posts messages to the agent, and can ask for a reply.

A state machine: each state is a function that waits for the next message.

ITT8060

Shared memory

Two computations update the same mutable data at the same time: a race.

An update of two fields is not atomic. A reader can see half of it.

A lock lets one computation at a time into the critical section.

ITT8060

Summary

  1. An event is a value: callbacks are added to it, and events are filtered, mapped and merged like collections.
  2. A sequence is pulled; an observable pushes.
  3. async { } describes a computation that can wait without holding a thread; it runs when it is started.
  4. Async.Parallel combines computations and keeps the order of its inputs.
  5. An agent keeps its state inside a message loop; state shared between threads needs a lock.
ITT8060

Homework, reading and next week

Homework 9 is out this week.

The notes continue with samples to study: memoization, image processing, a web crawler, parallel processing.

Reading: Microsoft Learn, "Async programming in F#" and "Events".

Next week: type providers and dynamic code generation.

ITT8060