Welcome   |   ASP.NET   |   Web Services   |   How Do I...?   |   Class Browser
  |   I want my samples in...   

How Do I...? Common Tasks QuickStart Tutorial

Go To...

How Do I...Use simple transactions in my application?

The easiest way to use transactions in your code is using TransactionScope. TransactionScope is used to transact a block of code. The follow code snippet uses TransactionScope in its simplest way.

		
	try
	{
	    using (TransactionScope ts = new TransactionScope())
	    {
	        //Do some transactional work
	        
	        //Call complete on the transaction scope
	        ts.Complete()
	    }
	}
	catch()
	{
	    //Handle exception
	}
C#

There are a few important things to note about this code:

  • The recommended way to use TranasctionScope is with the 'using' statement. Within the using block, all operations with transacted resources will automatically be part of the transaction.
  • Calling complete() on the TransactionScope object tells the system the transaction is ready to be committed. Failing to call complete() on the TransactionScope will rollback the transaction.
  • The transaction will automatically commit or abort at the end of the using block based on whether complete() was called or not.
  • Wrap the entire block of code with a try..catch. Any exceptions thrown within the using block will cause the transaction to rollback. The exception will then get thrown for the application code to deal with.

Here is a full example:

[This sample can be found at M:\web\users\Sites\AspnetQuickStart\v2.0\QuickStart\howto\samples\Transactions\TransactionScopeSample
To build this sample, open the SDK command prompt and navigate to the above path. Build the sample using the build tool msbuild passing the solution file as the first parameter: msbuild mySample.sln. The compiled executable will be found in the sub directory \bin directory.]




Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2005 Microsoft Corporation. All rights reserved.


Hosted by MaximumASP | Found a broken link? | Contact Us | Terms and conditions | Privacy Policy | Advertise with us
� 2000 - 2008  Mindcracker LLC. All Rights Reserved