Friday, June 10, 2005

Transactions in .NET 2.0

After procrastinating the installation of VS .NET 2005 beta 2 for almost a week now .. I finally got it installed and running on my laptop..

The first thing that caught my attention is the revised Transaction support. .Net v1.1 supported two transaction programming models.. explicit transaction programming model (using IDbTransaction interface) and Declarative transaction flow model(using System.EnterpriseServices). The explicit programming model cannot be used when you have distributed transactions. But the Declarative transaction comes with the price of COM+ hosting model which many Configuration Managers find intimidating ;). and it has the overhead of using DTC transaction even though only a single resource is involved. So there is no clean and easy way of transaction management in .Net 1.1.

.Net 2.0 addresses all the above issues with the addition of two new transaction managers Lightweight Transaction Manager LTM(similar to .Net 1.1 explicit programming model) and OleTx Transaction Manager OTM(Similar to .Net 1.1 Enterprise Services) and helper classes available in System.Transaction namespace. As developers we need to be aware only about the usage of System.Transaction namespace and .NET internally takes care of using the appropriate resource manager.

Suppose a object is accessing only a single durable resource(SQL server 2005) .NET would use LTM internally to provide the best throughput and performance. If at any point the object accesses another durable resource(MSMQ) then the transaction will automatically be promoted to use OTM. This transaction will remain in this state till its completion.

A simple usage of TransactionScope:

using(TransactionScope ts = new TransactionScope())
// do any transactional work here
// The transactional work could be spanning one resource or multiple resource.
// calling complete will commit the work.
ts .Complete();

Make sure to call the Complete() method or else your transaction will be rolled back..

One important thing worth noting is the existing enterprise services like Oracle, SQL server 2000 and MSMQ cannot participate in an LTM transaction. So by default they use only the OTM manager.

No comments: