Last active
April 30, 2019 17:04
-
-
Save alistairjevans/03e680ddcbcc99dde3cbeeea252d8cce to your computer and use it in GitHub Desktop.
MongoDB Lock - Lock Provider Signature
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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