Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.