Hierarchy of TransactionScope

旧城冷巷雨未停 提交于 2020-01-13 16:44:12

问题


Is it possible to have a hierarchy of transaction scopes?

If the outer transaction scope does a dispose, what will happen to changes made in the inner transaction scope?

My particular problem is that I have test code that runs code that has a transaction scope. When I call a second set of code with a transaction scope I get "Cannot access a disposed object. Transaction". Could it be that the dispose of the inner transaction scope is also disposing the outer transaction scope.


回答1:


I doubt this is what is happening. TransactionScopes can be nested as long as the underlying technology supports distributed transactions, if necessary. For instance, if you start a transaction and update some data in database A, and then you call a function, and inside that function, you create a new TransactionScope and insert some data into database B, then the inner transaction uses the "ambient" transaction that was already open. However, for this to work you need the Distributed Transaction Coordinator running (for SQL Servers). Also, SQL Server 2005 and above has the ability to start a transaction as a regular transaction and promote it to a distributed transaction if it needs to, whereas SQL 2000 will start all of them as distributed transactions because it doesn't have the ability to promote them.

When you have nested transactions, the whole transaction doesn't commit until the outer-most transaction is committed.

Here's some more info.

Take a look at TransactionScopeOption; that determines how the nested transaction interacts with outer transactions.




回答2:


When an outer transaction fails, all the inner ones will we rolled back. If you commit and inner one, and dispose the outer, the inner still rolls back. In fact the inner doesn't commit unless the outer one lets it by committing.

You are committing the outer one aren't you? See here for a good paper on this.




回答3:


Yes, it's possible to have a hierarchy of transaction scopes. This blog post explains how they work, in particular how the inner transaction scope should be instantiated and how the transactions complete & commit.

It is important to keep in mind the distinction between transactions and transaction scopes - by default (i.e. in the absense of TransactionScopeOption) you will only utilise a single transaction even when you nest transaction scopes.

Regarding the "disposed" error message, see this question.



来源:https://stackoverflow.com/questions/1334366/hierarchy-of-transactionscope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!