synchronizedAsync<T> function

FutureOr<T> synchronizedAsync<T>(
  1. Object monitor,
  2. FutureOr<T> action()
)

Runs the given action in a critical section, ensuring only one execution at a time per monitor object.

This function provides an easy and safe way to serialize access to a shared resource. It retrieves a lock associated with the monitor and queues the action to be executed when it's safe to do so.

Reentrant calls from the same Dart Zone are allowed (i.e., nested synchronized() calls on the same monitor will execute immediately).

Example:

final lockTarget = Object();

Future<void> criticalWrite() async {
  await synchronizedAsync(lockTarget, () async {
    // only one call at a time per lockTarget
    await writeToDatabase();
  });
}

Implementation

FutureOr<T> synchronizedAsync<T>(Object monitor, FutureOr<T> Function() action) {
  final lock = _lockRegistry.getLock(monitor);
  return lock.synchronizedAsync(action);
}