The following code sample demonstrates explicit and implicit locking, within and outside of transaction state.
// Lock objects outside transaction state. TimeSpan timeOut = TimeSpan.FromSeconds(10); context.Lock(obj1, LockType.Reserve, LockDuration.Transaction, timeOut); context.Lock(obj2, LockType.Shared, LockDuration.Transaction, timeOut); context.Lock(obj3, LockType.Shared, LockDuration.Session, timeOut); using (System.Data.IDbTransaction tran = context.BeginTransaction()) { // Lock an object in transaction state. context.Lock(obj4, LockType.Exclusive, LockDuration.Transaction, timeOut); coll1.Add(obj1); // Acquires an implicit exclusive lock on coll1. // Acquire an explicit update lock. This can only be done in transaction state. context.Lock(coll2, LockType.Update, LockDuration.Transaction, timeOut); coll2.Add(obj2); // No implicit lock, as coll2 is already locked. context.Unlock(obj2); // This is ignored in transaction state. context.Unlock(obj3); // This is ignored in transaction state. obj5.Attr1 = "X"; // Acquires an implicit exclusive lock. tran.Commit(); // Upgrades coll2’s update lock to exclusive, // commits the updates, // then unlocks coll1, coll2, obj1, obj2, obj4, and obj5. // obj3 remains locked as it has session duration. } context.Unlock(obj3); // This will unlock obj3. // Specify implicit update locks are to be used. context.SetImplicitUpdatingLockType(LockType.Update); using (System.Data.IDbTransaction tran = context.BeginTransaction()) { coll3.Add(obj2); // Acquires an implicit update lock on coll3. tran.Commit(); // Upgrades the update lock to an exclusive lock, // commits the update, // then unlocks coll3. } context.SetImplicitUpdatingLockType(LockType.Exclusive);