In C#, you can use try-catch-finally blocks, and perform your tidying up in the finally. (Which should execute no matter what).
You could achieve much the same thing by creating a class that implements IDisposable
, which gets the lock, and releases it when the disposing method is called. Then whenever you consume that class (which gets the lock), put in in a using block
using (RecordLockingThing myThing = new RecordLockingThing())
{
//DoStuff
}
//Now myThing is out of scope, and will have been disposed.
Just make sure your RecordLockingThing
correctly and safely releases the lock in the disposing method.
Another strategy might be not to mark record to lock them when opened, but to mark them as edited instead (or increment a revision number). Then you can allow more than one person to open the record. When someone submits an edit, make them submit the revision number too, if it matches, commit the edit and increment the revision, if not, report a "mid air collision", and either discard the edits (not very friendly), or try and let the user merge the records.
If edits are fairly rare compared to reads, the second strategy will be more useful in practice, as you'll never prevent a user from at least looking at a record, and there's no risk of orphaned locks.