Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MongoDB Lock - Lock Provider Signature
public class LockProvider
{
private readonly IMongoCollection<LockModel> collection;
public LockProvider(string mongodbConnString) {} // Collapsed
public async Task<IDisposable> AcquireLock(string resourceId)
{
// Determine the id of the lock
var lockId = $"lock_{resourceId}";
var distributedLock = new DistributedLock(collection, lockId);
var startLockAcquireTime = DateTime.Now;
// Try and acquire the lock
while (!await distributedLock.AttemptGetLock())
{
// If we failed to acquire the lock, wait a moment.
await Task.Delay(100);
// Only try to acquire the lock for 10 seconds
if ((DateTime.Now - startLockAcquireTime).TotalSeconds > 10)
{
throw new ApplicationException($"Could not acquire lock for {resourceId} within the timeout.");
}
}
// This will only return if we have the lock.
return distributedLock;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.