问题
I have read that the default isolation level for ADO.NET (when transactions aren't used i.e. each statement is executed as an atomic operation) is 'READ COMMITTED' and the default isolation level for TransactionScope (http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx) is 'SERIALIZABLE'. Is there a reason for this?
I have read many webpages on this subject, but I have not yet found an answer to my specific question.
回答1:
A Transaction is a unit of work, which basically means there are several activities are performed with in the scope. For example, Booking a Cart involves checking the product, checking the on-hand quantity, calculating shipping costs and updating the financial accounts. All of these actions should go as one or none, if any of them had a phantom reads like in case of Isolation level 'READ COMMITTED' then it puts data in a stale state. If 'SERIALIZED' scope is used then it will prevent any updates to the entities involved while in transaction.
In a case, where you are looking at Financial reports for a month, then 'READ COMMITTED' Isolation level works, because you are looking at existing data and not making too many modifications, even phantom reads wouldn't create much difference in the reports.
回答2:
The reason is that a Transaction scope can span multiple (sub)transactions that all are coordinated with a distributed transaction coordinator (MS-DTC). Most of the times you'll want to be sure that all subtransctions are working with the same data, even if a commit happened between them.
For example a service that has 3 methods: checkbalance, increasebalance & decreasebalance. Each method starts a transaction, opens a database connections, executes a SQL, closes the connection and commits the transaction.
A typical scenario would then be for a client of this service to:
- start master transaction
- check balance of account 1
- decrease balance of account 1
- increase balance of account 2
- commit master transaction
IsolationLevel.Serializable will make sure that all service calls will a) start from the same data and b) no one else is allowed to alter that data while the master transaction is running.
IsolationLevel.ReadCommitted can cause the balance of account 1 to go below zero if someone else decreased the balance with a sufficient amount and committed that transaction between the check and the decrease.
来源:https://stackoverflow.com/questions/17874968/ado-net-isolation-level-v-transactionscope-isolation-level