withLock<T> method
Convenience method for protecting a function with a lock.
This method guarantees a 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, when those exceptions occur.
Implementation
Future<T> withLock<T>(Future<T> Function() criticalSection) async {
await lock();
try {
return await criticalSection();
} finally {
release();
}
}