Page view counter

These tutorials demonstrate selected features in ASP.NET version 2.0, but they are compatible with later versions of ASP.NET as well. For the current documentation, see the ASP.NET portal on the MSDN Web site.

 

 

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

How Do I...? Common Tasks QuickStart Tutorial

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 scope As TransactionScope = New TransactionScope()
            'Do some transactional work

            'Call complete on the transaction scope
            scope.Complete()
        End Using
    Catch
        'Handle exception
    End Try
VB

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 D:\quickstarts.asp.net\QuickStartv20\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.