
async Isn't a Background Thread: Dart's Event Loop and When You Need an Isolate
- كاتب موثّق
- Dart 3
محتويات المقال
async, and still, each time the list arrives, the loading spinner freezes for a moment and a scroll in progress stutters. The review comment on the fix reads "it can't be the parsing, it's already async". It is the parsing. async was never going to move it anywhere.
The common misconception
async sends its work to the background. As long as the heavy code sits inside an async function and the caller awaits it, the UI stays free.
async looks like "runs in the background". The waiting does happen elsewhere. Your Dart code doesn't.
What actually happens
One isolate, one thread, one event loop
async function. Flutter adds its own events to that queue: on a 60 Hz device, a "paint frame" event 60 times per second. If one event takes too long, the frame events behind it wait, and the user sees .
An async function runs synchronously until its first await
async doesn't start anything new. The Dart docs put it plainly: an async function runs synchronously until the first await. Run this:
Future<void> work() async { print('2: work starts, synchronously'); await Future<void>.delayed(Duration.zero); print('4: after the await, same isolate');}void main() { print('1: main'); work(); print('3: main continues');}work() runs its first line right away, on the caller's stack. The await suspends the function and returns a Future to the caller, which carries on. When the awaited future completes, the rest of work() is scheduled to run later, on the same event loop. At no point does a second thread appear.
await waits; it doesn't compute
jsonDecode, sorting 50,000 items, filtering a big list, resizing an image. It runs on the event loop, and while it runs, nothing else does. No frame, no tap handler, no timer. Wrapping it in Future(() => work()) doesn't help either: that constructor runs the computation later through Timer.run, on the same isolate. It changes when the work runs, not where.
Isolates: a second event loop with its own memory
Isolate.run does the whole round trip for you: it spawns a worker isolate, runs your function there, returns the result to the main isolate and shuts the worker down. The result comes back through Isolate.exit, which hands it over without copying it.
import 'dart:convert';Future<List<Object?>> loadCatalog(Future<String> Function() fetch) async { final body = await fetch(); // I/O wait: frames keep coming // Still the main isolate: no frame until the decode returns return jsonDecode(body) as List<Object?>;}import 'dart:convert';import 'dart:isolate';Future<List<Object?>> loadCatalog(Future<String> Function() fetch) async { final body = await fetch(); // I/O wait: frames keep coming // The decode runs on a worker isolate; the main one stays free return Isolate.run(() => jsonDecode(body) as List<Object?>);}Future(() => …) variant behaved the same. With Isolate.run, the whole call took longer, about 290 to 340 ms including starting the worker, but the timer kept firing as often as it did with the app idle.
async runs the function on a background thread | await |
await keeps the UI responsive | |
Future(() => work()) moves work off the UI | |
Isolate.run makes the work faster |
How to apply it in your project
Separate waiting from computing Read your asyncfunctions line by line. Eachawaiton I/O is waiting, which is cheap. Each decode, loop, sort or image operation after it is computing, which blocks the main isolate for as long as it takes.Measure before you move anything Run the app in profile mode and open the DevTools Performance view, which marks frames slower than about 16 ms (on a 60 Hz screen) with a red overlay. Look at which Dart code ran in those frames. Small payloads rarely need an isolate. Move the heavy, pure part with Isolate.run Pass plain data in (a string, a list, bytes) and return plain data out. Keep the closure small, or call a top-level function, so it doesn't drag thisalong.Keep UI work on the main isolate Widgets, rootBundleassets and all other UI work are tied to the main isolate. Load the asset there, then send its contents to the worker. For the same job repeated many times, a long-lived isolate fromIsolate.spawnwith ports avoids paying the spawn cost on every call.
Key takeaways
asyncdoesn't create a thread: the function runs on the caller's isolate until its firstawait.awaitfrees the event loop only while waiting; the code after it runs on the same isolate.CPU-heavy work on the main isolate delays frames and taps, asyncor not.Isolate.runmoves work to a worker with its own memory, at the cost of a spawn and a copy.Send plain data to isolates, keep UI work on the main one, and use computewhen you also target the web.
التعليقات (0)