Created
April 30, 2019 17:35
-
-
Save alistairjevans/d84c1d47256b88cca2c82f8acc5fe05e to your computer and use it in GitHub Desktop.
DistributedLock with concurrency handling
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
try | |
{ | |
var response = await collection.FindOneAndUpdateAsync<LockModel>( | |
// Collapsed | |
); | |
// If the result of the FindOneAndUpdateAsync is null, then that means there was no record | |
// before we ran our statement, so we now have the lock. | |
// If the result is not null, then it means a document for the lock already existed, so someone else has the lock. | |
if (response == null) | |
{ | |
return true; | |
} | |
return false; | |
} | |
catch (MongoCommandException ex) | |
{ | |
// 11000 == MongoDB Duplicate Key error | |
if (ex.Code == 11000) | |
{ | |
// Two threads have tried to acquire a lock at the exact same moment on the same key, | |
// which will cause a duplicate key exception in MongoDB. | |
// So this thread failed to acquire the lock. | |
return false; | |
} | |
throw; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment