Skip to content

Instantly share code, notes, and snippets.

@alistairjevans
Last active April 30, 2019 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alistairjevans/03e680ddcbcc99dde3cbeeea252d8cce to your computer and use it in GitHub Desktop.
Save alistairjevans/03e680ddcbcc99dde3cbeeea252d8cce to your computer and use it in GitHub Desktop.
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