Skip to content

Instantly share code, notes, and snippets.

@alistairjevans
Last active May 1, 2019 11:29
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/dcca124f1d53109bc23980e9ceb1a40c to your computer and use it in GitHub Desktop.
Save alistairjevans/dcca124f1d53109bc23980e9ceb1a40c to your computer and use it in GitHub Desktop.
Distributed lock with added expiry.
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)
.SetOnInsert(x => x.ExpireAt, DateTime.UtcNow.AddMinutes(1)),
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
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment