synchronizedAsync<T> method
Executes the action
within an asynchronous synchronized block.
Only one action
may execute at a time per lock. If the current Zone
has already acquired the lock, the function is treated as reentrant and allowed.
Otherwise, the action is queued and executed when the lock becomes available.
Example:
await lock.synchronizedAsync(() async {
// Do something asynchronous
});
Implementation
Future<T> synchronizedAsync<T>(FutureOr<T> Function() action) {
final completer = Completer<T>();
// Handle reentrancy: if the current zone already holds the lock, execute immediately.
if (_isLocked && _currentLockingZone == Zone.current) {
_reentrantCount++;
try {
completer.complete(action());
} catch (e, s) {
completer.completeError(e, s); // Propagate original error
} finally {
_reentrantCount--;
// The lock is not released here; it's released by the original acquiring task.
}
return completer.future;
}
// If not reentrant, or if lock is not held by current zone, queue the request.
final request = _LockRequest<T>(action, completer);
_queue.add(request);
_tryAcquireLockAndRun(); // Attempt to run immediately if lock is free
return completer.future;
}