21.10 · The main thread in code: hang watchdogs, actor hops and quality of service
The main-thread contract is easy to state and easy to break. You can measure the break from inside the process, and the cost of moving work off the main thread is not zero.
Mental model. Detect stalls with a heartbeat, hop deliberately, and tag work with the quality of service it deserves.
Detecting and moving work
A watchdog for hangs, and what an actor hop costs.
- How can an app detect its own main-thread hangs, and what are the limits of doing it in-process?
A watchdog is a background thread that repeatedly asks the main queue to record a heartbeat (DispatchQueue.main.async { lastPong = now }), sleeps briefly, and… - Is moving work off the main actor free, and what does it cost to hop back to it many times?
Calling a @MainActor function from another task is a suspension plus an enqueue: the caller gives up its thread, the work is queued on the main executor, and…
More in Performance & energy
- 21.1 · Measure first: the method, the metrics and the noise
- 21.2 · Instruments templates, signposts and XCTMetric
- 21.3 · MetricKit, Organizer and a performance culture
- 21.4 · SwiftUI invalidation and long lists
- 21.5 · The costs that show up in profiles: collections, strings, formatters, JSON, images and disk
- 21.6 · Energy: CPU wake-ups, timers, radios, location and thermal state
- 21.7 · App size: thinning, on-demand resources and the binary
- 21.8 · Writing benchmarks you can believe: the optimiser, build settings and growth tests
- 21.9 · Memory you can count: allocations, dirty versus clean pages and decoded images
- 21.11 · Launch: lazy initialisation and measuring from process start
- 21.12 · Counting wake-ups: why polling costs energy even when the work is tiny