This is just an extension to this answer.
using System; using System.Threading; using System.Threading.Tasks; public class SemaphoreLocker { private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); public async Task LockAsync(Func<Task> worker) { await _semaphore.WaitAsync(); try { await worker(); } finally { _semaphore.Release(); } } } Usage:
public class Test { private static readonly SemaphoreLocker _locker = new SemaphoreLocker(); public async Task DoTest() { await _locker.LockAsync(async () => { // [asyn] calls can be used within this block // to handle a resource by one thread. }); } }