开发者

What are the good and bad points of TransactionScope?

What a开发者_高级运维re the good and bad points of the TransactionScope class in C#?

Thanks.


Some advantages from MSDN :

TransactionScope Benefits

  • The code inside the transactional scope is not only transactional, it is also promotable. The transaction starts with the LTM and System.Transactions will promote it as required, according to the nature of its interaction with the resources or remote objects.
  • The scope is independent of the application object model—any piece of code can use the TransactionScope and thus become transactional. There is no need for special base class or attributes.
  • There is no need to enlist resources explicitly with the transaction. Any System.Transactions resource manager will detect the ambient transaction created by the scope and automatically enlist.
  • Overall, it is a simple and intuitive programming model even for the more complex scenarios that involve transaction flow and nesting.


Good side:

Can do transactions beyond database context. Insert record into db. Write file to disk.

Bad side:

Requires MSDTC access on client machine, where TransactionScope is used.


Just to add to / clarify the points Incognito makes:

  • TransactionScopes make the implementation of ACID transactions simple (i.e. so you don't need to write explicit "rollback" or cleanup code)
  • TransactionScope can coordinate resources such as Databases, Message Queues and Transactional File Systems under a transaction
  • Re TransactionScopes are intuitive - resources such as SQL etc will automatically / seamlessly detect the ambient transaction and enlist as available.

The only 'bad' side is that you need to be aware that:

  • The default isolation level of TransactionScope is READ SERIALIZABLE, which is usually too 'strong' and can cause blocking and deadlocking. Would recommend using ReadCommitted for most transactions.
  • TransactionScope will escalate a transaction to DTC if more than one database / more than one concurrent connection / more than one resource (e.g. SQL and MSMQ) are used in a TransactionScope. But you can usually avoided in Single Threaded / single database scenarios by closing connections before opening a new one (or keeping one connection open throughout, which isn't recommended).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜