/// <summary> /// Executes provided function as critical section, acquiring the specified lock, executing a statement, and then /// releasing the lock. /// </summary> /// <param name="lock">Synchronization object to use.</param> /// <param name="action">Asynchronous action to execute.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// Task which is completed after the operation has been performed and the lock has been released. /// </returns> public static async Task SynchronizedAsync(this ILockAsync @lock, AsyncAction action, CancellationToken cancellationToken) { await @lock.LockAsync(cancellationToken); try { await action.InvokeAsync(cancellationToken); } finally { @lock.Release(); } }
/// <summary> /// Executes provided function as critical section, acquiring the specified lock, executing a statement, and then /// releasing the lock. /// </summary> /// <param name="lock">Synchronization object to use.</param> /// <param name="func">Asynchronous function to execute.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// Task which is completed after the operation has been performed and the lock has been released. /// </returns> public static async Task <T> SynchronizedAsync <T>(this ILockAsync @lock, AsyncFunc <T> func, CancellationToken cancellationToken) { await @lock.LockAsync(cancellationToken); try { return(await func(cancellationToken)); } finally { @lock.Release(); } }