Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
transaction

How to use TransactionScope

Educative Answers Team

Transaction

Before the TransactionScope class can be understood, some background knowledge is required.

A transaction is a set of steps that make up one work unit. This means that for a transaction, either all of its steps need to be successfully completed or none of them. Therefore, it is considered a single work unit.

Transactions have a set of properties. These properties are Atomicity, Consistency, Isolation, and Durability. Together, they make up the acronym, ACID.

  1. Atomicity means that all steps need to be completed. In case a step fails, all related work that has been completed needs to be rolled back.
  2. Consistency means that the database has to be appropriately changed upon transaction completion.
  3. Isolation means that all transactions are to be operated independently of each other.
  4. Durability means that the effects of the transaction should be permanent. To clarify, this statement implies that in case of failure, data is recoverable.

TransactionScope

TransactionScope is a class in the System.Transaction namespace. A code-block can be made transactional using this class. The code within the implementation will be considered one transaction.

Implementation

The following code shows how this class can be used.

using (var transactionScope = new System.Transactions.TransactionScope())
{
  try
  {
    //Write code here which is needed to be transactional

    transactionScope.Complete(); //Call this function once transaction is complete
  }
  catch(Exception ex)
  {
    //If an exception is thrown, Complete() is not called, and the transaction is rolled back
  }
}

In case an exception is raised within the scope before the complete function is called, the transaction will be rolled back.

RELATED TAGS

c#
transaction
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring