Skip to content

Instantly share code, notes, and snippets.

@alistairjevans
Created April 30, 2019 17:35
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/d84c1d47256b88cca2c82f8acc5fe05e to your computer and use it in GitHub Desktop.
Save alistairjevans/d84c1d47256b88cca2c82f8acc5fe05e to your computer and use it in GitHub Desktop.
DistributedLock with concurrency handling
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