using System.Threading.Tasks;
var _lock = new ReentrantAsyncLock.ReentrantAsyncLock();
Log($"Obtain the lock before entering the for loop");
await using (await _lock.LockAsync(CancellationToken.None))
for (int i = 0; i < 100; ++i)
Log(i, "Try to obtain the lock");
await using (await _lock.LockAsync(CancellationToken.None))
Log(i, "Obtained the lock. Start waiting for 1ms");
await Task.Delay(TimeSpan.FromMilliseconds(1));
Log(i, "Waiting finished.");
Log("The loop finished successfully. Release the lock");
Log("The lock is completely released. Exit the main method");
static void Log(string msg)
Console.WriteLine($"[ThreadId={Thread.CurrentThread.ManagedThreadId,-2}] {msg}");
static void Log(int iteration, string msg)
Console.WriteLine($"[i={iteration,-2},ThreadId={Thread.CurrentThread.ManagedThreadId,-2}] {msg}");