Using a SQL Server Database Transaction as a C# Lock

Maydaygah

New Member
I'm moving a website to multiple instances. This means I can't use a \[code\]lock\[/code\] anymore to make sure a service doesn't run on top of itself. So I need a way to lock across instances.I should probably use a background worker with message queues but I feel like that's overkill for this one service. I'm wondering if I could somehow use a database transaction as a lock. I don't care about speed - I want it to be simple & work.Here's what I'm thinking of doing:\[code\]public class MultiInstanceLock : IDisposable{ private readonly string lockId; private Transaction transaction; private LockEntity lockEntity; public MultiInstanceLock(String _lockId) { lockId = _lockId; transaction = new Transaction(IsolationLevel.RepeatableRead, lockId); lockEntity = new LockEntity(lockId); if(lockEntity.IsNew) lockEntity.Id = lockId; lockEntity.LockedOn = DateTime.Now; lockEntity.Save(); } public void Dispose() { if (lockEntity != null) { lockEntity.UnlockedOn = DateTime.Now; lockEntity.Save(); } if(transaction != null) transaction.Commit(); }}\[/code\]Here's the usage:\[code\]using(var l = new MultiInstanceLock("Foo")){ ...do foo...}\[/code\]Would this work? Is there a better way?Already I'm noticing that the transaction would apply to any DB access inside my using statement, which is a bummer.
 
Back
Top