How and how to use TransactionScope in C #

Source: Internet
Author: User

In the era of. NET 1.1, there are no TransactionScope classes, so much of the processing of transactions is given to SqlTransaction and SqlConnection, each transaction based on each connection. This design is not very good for transactional behavior that spans multiple assemblies or multiple methods, and requires that transactions and database connections be passed in as parameters.

After. NET 2.0, the advent of the TransactionScope class greatly simplifies the design of the transaction. The sample code is as follows:

static void Main (string[] args)        {            using (TransactionScope ts = new TransactionScope ())            {                USERBLL u = new U SERBLL ();                TEACHERBLL t = new Teacherbll ();                U.add ();                T.add ();                Ts.complete ();            }        }

You only need to write the logical block that requires the transaction package in the using (TransactionScope ts = new TransactionScope ()). As can be seen from this notation, TransactionScope implements the IDispose interface. The Ts.complete () method is called unless it is displayed. Otherwise, the system does not automatically commit the transaction. If complete () is not called after the code runs out of the block, the transaction is automatically rolled back. In this transaction block, the U.add () method and T. No transaction classes are used inside the ADD () method.

TransactionScope is based on the current thread and, in the current thread, calls the Transaction.Current method to see the information for the current transaction. Specifically about the use of TransactionScope, which has its member methods and properties, you can view MSDN.

The TransactionScope class can be nested, and if it is to be nested, you need to specify the TransactionScopeOption parameter in a nested transaction block. The default parameter is required.

The specific meaning of this parameter can be referenced by Http://msdn.microsoft.com/zh-cn/library/system.transactions.transactionscopeoption (v=vs.80). aspx

For example, the following code:

static void Main (string[] args)        {            using (TransactionScope ts = new TransactionScope ())            {                Console.WriteLine (Transaction.Current.TransactionInformation.LocalIdentifier);                USERBLL u = new Userbll ();                TEACHERBLL t = new Teacherbll ();                U.add ();                using (TransactionScope ts2 = new TransactionScope (transactionscopeoption.required))                {                    Console.WriteLine ( Transaction.Current.TransactionInformation.LocalIdentifier);                    T.add ();                    Ts2.complete ();                }               Ts.complete ();            }        }

When the transactionscopeoption of the nested class's TransactionScope is required, the following results can be seen, and their transaction IDs are the same. And only when 2 TransactionScope are complete can they be truly successful.

If the transactionscopeoption is set to RequiresNew, the nested transaction block and the outer transaction block are independent of each other.

static void Main (string[] args)        {            using (TransactionScope ts = new TransactionScope ())            {                Console.WriteLine (Transaction.Current.TransactionInformation.LocalIdentifier);                USERBLL u = new Userbll ();                TEACHERBLL t = new Teacherbll ();                U.add ();                using (TransactionScope ts2 = new TransactionScope (transactionscopeoption.requiresnew))                {                    Console.WriteLine (Transaction.Current.TransactionInformation.LocalIdentifier);                    T.add ();                    Ts2.complete ();                }              Ts.complete ();            }        }

As you can see, their transaction IDs are not the same.

TransactionScopeOption set to suppress is a transaction that cancels the current chunk and is rarely used.

For database operations between multiple different servers, TransactionScope relies on the DTC (distributed Transaction Coordinator) service to complete transactional consistency.

But for single-server data, the TransactionScope mechanism is more complex. The main use is the thread static characteristics. The thread static attribute ThreadStaticAttribute lets the CLR know that the access to the static fields it flags is dependent on the current thread and independent of the other threads. Since the data stored in the thread static field is only visible to code running in the same threads where the data is stored, you can use such fields to pass other data from one method to another method called by the first method, without worrying about other threads destroying its work. TransactionScope will store the current Transaction in the thread static field. When SqlCommand is later instantiated (before it is removed from the thread-local store in this TransactionScope), the SqlCommand examines the thread's static field to find the existing Transaction and, if present, is included in the Transaction. In this way, TransactionScope and SqlCommand are able to work together so that developers do not have to pass Transaction display to SqlCommand objects. In fact, the mechanisms used by TransactionScope and SqlCommand are very complex. For details, refer to article Http://www.microsoft.com/china/MSDN/library/netFramework/netframework/NETMattersSep.mspx?mfr=true

Professional C # 4 and. NET 4, published by Wrox, also introduces some of the ways in which TransactionScope can be used.

How and how to use TransactionScope in C #

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.