views:

684

answers:

1

I would like some advice from anyone experienced with implementing something like "pessimistic locking" in an asp.net application. This is the behavior I'm looking for:

  1. User A opens order #313
  2. User B attempts to open order #313 but is told that User A has had the order opened exclusively for X minutes.

Since I haven't implemented this functionality before, I have a few design questions:

  • What data should i attach to the order record? I'm considering:
    • LockOwnedBy
    • LockAcquiredTime
    • LockRefreshedTime

I would consider a record unlocked if the LockRefreshedTime < (Now - 10 min).

  • How do I guarantee that locks aren't held for longer than necessary but don't expire unexpectedly either?

I'm pretty comfortable with jQuery so approaches which make use of client script are welcome. This would be an internal web application so I can be rather liberal with my use of bandwidth/cycles. I'm also wondering if "pessimistic locking" is an appropriate term for this concept.

+4  A: 

It sounds like you are most of the way there. I don't think you really need LockRefreshedTime though, it doesn't really add anything. You may just as well use the LockAcquiredTime to decide when a lock has become stale.

The other thing you will want to do is make sure you make use of transactions. You need to wrap the checking and setting of the lock within a database transaction, so that you don't end up with two users who think they have a valid lock.

If you have tasks that require gaining locks on more than one resource (i.e. more than one record of a given type or more than one type of record) then you need to apply the locks in the same order wherever you do the locking. Otherwise you can have a dead lock, where one bit of code has record A locked and is wanting to lock record B and another bit of code has B locked and is waiting for record A.

As to how you ensure locks aren't released unexpectedly. Make sure that if you have any long running process that could run longer than your lock timeout, that it refreshes its lock during its run.

The term "explicit locking" is also used to describe this time of locking.

andynormancx
+1 great answer, thanks. i'll leave the question unanswered for 24 hours in hopes of encouraging more responses.
Ken Browning
Beware of the person that goes to lunch/vacation while leaving their browser open. Consider whether you need some kind of UI for users or a manager to break other people's locks. (Speaking from experience.)
Jason DeFontes