Skip to content

Instantly share code, notes, and snippets.

@alistairjevans
Created April 30, 2019 17:08
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/30add9aee9cdb75dd94cc745bb89105a to your computer and use it in GitHub Desktop.
Save alistairjevans/30add9aee9cdb75dd94cc745bb89105a to your computer and use it in GitHub Desktop.
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