【C# 锁】C# 异步锁
原文链接:https://github.com/StephenCleary/AsyncEx
A lot of developers start using this library for AsyncLock
, an async-compatible mutual exclusion mechanism. Using AsyncLock
is straightforward:
private readonly AsyncLock _mutex = new AsyncLock();
public async Task UseLockAsync()
{
// AsyncLock can be locked asynchronously
using (await _mutex.LockAsync())
{
// It's safe to await while the lock is held
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
AsyncLock
also fully supports cancellation:
public async Task UseLockAsync()
{
// Attempt to take the lock only for 2 seconds.
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));
// If the lock isn't available after 2 seconds, this will
// raise OperationCanceledException.
using (await _mutex.LockAsync(cts.Token))
{
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
AsyncLock
also has a synchronous API. This permits some threads to acquire the lock asynchronously while other threads acquire the lock synchronously (blocking the thread).
public async Task UseLockAsync()
{
using (await _mutex.LockAsync())
{
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
public void UseLock()
{
using (_mutex.Lock())
{
Thread.Sleep(TimeSpan.FromSeconds(1));
}
}
编程是个人爱好