withReadLock<T> method

Future<T> withReadLock<T>(
  1. Future<T> criticalSection()
)

Convenience method for protecting a function with a read lock.

This method guarantees a read lock is always acquired before invoking the criticalSection function. It also guarantees the lock is always released.

A critical section should always contain asynchronous code, since purely synchronous code does not need to be protected inside a critical section. Therefore, the critical section is a function that returns a Future. If the critical section does not need to return a value, it should be defined as returning Future<void>.

Returns a Future whose value is the value of the Future returned by the critical section.

An exception is thrown if the critical section throws an exception, or an exception is thrown while waiting for the Future returned by the critical section to complete. The lock is released even when exceptions occur.

Implementation

Future<T> withReadLock<T>(Future<T> Function() criticalSection) async {
  await read();
  try {
    return await criticalSection();
  } finally {
    release();
  }
}