摘要:
Specification of the concurrency control for a transaction.
备注:
Values of this type are used by the Telerik.OpenAccess.ITransactionProperties.Concurrency property. This enum contains all concurrency settings which can be used by a database backend.
In general, there are two main concurency modes, which can both be used within a transaction: OPTIMISTIC PESSIMISTIC
Using optimistic transactions will cause the system to implicitly keep track of accessed objects and their modifications. Conflicts throughout the concurrent execution of operations are detected late. Conflicts will lead to an Telerik.OpenAccess.Exceptions.OptimisticVerificationException during Telerik.OpenAccess.ITransaction.Commit().
Using pessimistic transactions locks are set in the database backend when objects are accessed for read or write by a client. Conflicts are detected early and will cause a Telerik.OpenAccess.Exceptions.LockNotGrantedException. For instance, GetObjectById will throw an exception when the object is already locked against reading access by another transaction.
For optimistic mode, Telerik.OpenAccess.TransactionMode.OPTIMISTIC_NO_LOST_UPDATES has to be used. For pessimistic mode, either Telerik.OpenAccess.TransactionMode.PESSIMISTIC_EXPLICIT or Telerik.OpenAccess.TransactionMode.PESSIMISTIC_WRITE_LOCK_WHEN_FETCHED has to be used.
With PESSIMISTIC_WRITE_LOCK_WHEN_FETCHED the database automatically applies exclusive locks, when objects are read from the datastore. Locks are released atomically during commit or rollback, respectively.
With PESSIMISTIC_EXPLICIT the database does not apply any exclusive locks automatically before commit. The Telerik.OpenAccess.ITransaction.Lock(System.Object,Telerik.OpenAccess.LockMode) method can be used to obtain exclusive locks manually. All locks are released atomically during commit or rollback, respectively. Although no automatic locks are set, a write or delete operation of a PESSIMISTIC_EXPLICIT transaction may be inhibited by locks held by other transactions.
For more information please refer to the Open Access .NET Programmers Guide.
Telerik.OpenAccess.IObjectScope.TransactionProperties
数据库并发控制分两种,一种是乐观并发(OPTIMISTIC),一种是悲观并发(PESSIMISTIC)
乐观并发是不加锁,但是获取数据时会带一个版本戳,提交修改时如果发现提交的版本戳和数据库当前版本戳不一致,就说明数据已经发生变化。
悲观并发是使用锁定,试图修改被别人锁定的数据不会成功。要获取锁-修改-提交。那个枚举就是包含了乐观并发的一种方式,和悲观并发的三种方式。
1. OPTIMISTIC_NO_LOST_UPDATES 这就是提交时才检查版本戳,不一致就扔OptimisticVerificationException异常,说明数据已被修改。2. PESSIMISTIC_EXPLICIT 这是不自动加锁,需要自己主动调用ITransaction.Lock()对数据加写锁。如果试图修改已经被别人锁定的数据,就会扔LockNotGrantedException。
3. PESSIMISTIC_WRITE_LOCK_WHEN_FETCHED 这是取数据时就自动加写锁,其它同上。
4. PESSIMISTIC_WRITE_LOCK_WHEN_FETCHED_FIRST 这是取第一条数据时会自动加写锁,之后不会。其它同上。
说应用场景,一般来说更鼓励使用乐观并发,因为不加锁性能最好。但是它要到提交的时候才知道失败。所以如果事务比较简单,那用这种方式比较高效。
如果是较为复杂的事务,不想在提交时才知道失败,或者事务过程中还需要执行其它数据库以外的操作,那就用悲观方式,先锁定再修改,保证最后提交能够成功。
至于锁定用什么方式,这就看具体的需求,手动控制肯定最精确,但是麻烦。取数据就自动锁定的话就可能加一些不必要的锁影响性能。而如果你的业务逻辑和实体能设计好,比如对一类业务来说存在一个主要的锁定目标(或者说聚合根),事务开始先获取它,其它关联数据也不会有其它地方修改,那就可以用取第一条数据时自动加锁的方式。