Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MongoDB Lock - DistributedLock - Part 1
public class DistributedLock : IDisposable
{
private readonly IMongoCollection<LockModel> collection;
private readonly string lockId;
public DistributedLock(IMongoCollection<LockModel> collection, string lockId)
{
this.collection = collection;
this.lockId = lockId;
}
public async Task<bool> AttemptGetLock()
{
var response = await collection.FindOneAndUpdateAsync<LockModel>(
// Find a record with the lock ID
x => x.Id == lockId,
// If our 'upsert' creates a document, set the ID to the lock ID
Builders<LockModel>.Update.SetOnInsert(x => x.Id, lockId),
new FindOneAndUpdateOptions<LockModel>
{
// If the record doesn't exist, create it.
IsUpsert = true,
// Specifies that the result we want is the record BEFORE it
// was created (this is important).
ReturnDocument = ReturnDocument.Before
});
// 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;
}
public void Dispose()
{
// Delete the document with the specified lock ID, effectively releasing the lock.
collection.DeleteOne(x => x.Id == lockId);
}
}
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.